Skip to content

Commit 8ec2bfc

Browse files
committed
Update README.md
1 parent 676ad64 commit 8ec2bfc

File tree

1 file changed

+202
-1
lines changed

1 file changed

+202
-1
lines changed

README.md

Lines changed: 202 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3616,7 +3616,208 @@ Few events are :
36163616
<b><a href="#table-of-contents">↥ back to top</a></b>
36173617
</div>
36183618

3619-
#### Q. Explain Error Handling approaches in Node.js?
3619+
## Q. What is Error Handling in Node.js?
3620+
3621+
An error is any problem given out by the program due to a number of factors such as logic, syntax, timeout, etc. An error in Node.js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError, RangeError, TypeError, URIError, EvalError, and SyntaxError.
3622+
3623+
User-defined errors can also be created by extending the base Error object, a built-in error class, or another custom error. In general, Node.js errors are divided into two distinct categories: operational errors and programmer errors.
3624+
3625+
**1. Operational Errors:**
3626+
3627+
Operational errors represent runtime problems. These errors are expected in the Node.js runtime and should be dealt with in a proper way. Here\'s a list of common operational errors:
3628+
3629+
* failed to connect to server
3630+
* failed to resolve hostname
3631+
* invalid user input
3632+
* request timeout
3633+
* server returned a 500 response
3634+
* socket hang-up
3635+
* system is out of memory
3636+
3637+
**2. Programmer Errors:**
3638+
3639+
Programmer errors are what we call bugs. They represent issues in the code itself. Here\'s a common one for Node.js, when you try reading a property of an undefined object. It\'s a classic case of programmer error. Here are a few more:
3640+
3641+
* called an asynchronous function without a callback
3642+
* did not resolve a promise
3643+
* did not catch a rejected promise
3644+
* passed a string where an object was expected
3645+
* passed an object where a string was expected
3646+
* passed incorrect parameters in a function
3647+
3648+
<div align="right">
3649+
<b><a href="#table-of-contents">↥ back to top</a></b>
3650+
</div>
3651+
3652+
## Q. Explain Error Handling approaches in Node.js?
3653+
3654+
**1. Using try-catch block:**
3655+
3656+
Try-catch declaration is basically used to handle runtime errors in node.js. If the code in the try block throws an exception, the code in the catch block will be executed. It can be extended using finally clause. The finally clause is statements that are executed after the try statement completes.
3657+
3658+
**Example:**
3659+
3660+
```js
3661+
function square(num) {
3662+
if (typeof num !== "number") {
3663+
throw new TypeError(`Expected number but got: ${typeof num}`);
3664+
}
3665+
3666+
return num * num;
3667+
}
3668+
3669+
try {
3670+
square("10");
3671+
} catch (err) {
3672+
console.log(err.message); // Expected number but got: string
3673+
}
3674+
```
3675+
3676+
**2. Using promises:**
3677+
3678+
Promise in Node.js is a contemporary way to handle errors, and it is usually preferred compared to callbacks. In the function, we will return a promise, which is a wrapper to our primary logic. We pass two arguments while defining the Promise object:
3679+
3680+
* resolve — used to resolve promises and provide results
3681+
* reject — used to report/throw errors
3682+
3683+
**Example:**
3684+
3685+
```js
3686+
function square(num) {
3687+
return new Promise((resolve, reject) => {
3688+
setTimeout(() => {
3689+
if (typeof num !== "number") {
3690+
reject(new TypeError(`Expected number but got: ${typeof num}`));
3691+
}
3692+
3693+
const result = num * num;
3694+
resolve(result);
3695+
}, 100);
3696+
});
3697+
}
3698+
3699+
square("10")
3700+
.then((result) => console.log(result))
3701+
.catch((err) => console.error(err));
3702+
```
3703+
3704+
Output:
3705+
3706+
```js
3707+
TypeError: Expected number but got: string
3708+
at Timeout._onTimeout (C:\node\index.js:5:16)
3709+
at listOnTimeout (internal/timers.js:554:17)
3710+
at processTimers (internal/timers.js:497:7)
3711+
```
3712+
3713+
**3. Error-first callbacks:**
3714+
3715+
Node.js uses an error-first callback convention in most of its asynchronous methods to ensure that errors are checked properly before the results of an operation are used. This callback function is usually the last argument to the function that initiates an asynchronous operation, and it is called once when an error occurs or a result is available from the operation.
3716+
3717+
**Example:**
3718+
3719+
```js
3720+
const fs = require('fs');
3721+
3722+
fs.readFile('/path/to/file.txt', (err, result) => {
3723+
if (err) {
3724+
console.error(err);
3725+
return;
3726+
}
3727+
3728+
// Log the file contents if no error
3729+
console.log(result);
3730+
});
3731+
```
3732+
3733+
Output
3734+
3735+
```js
3736+
[Error: ENOENT: no such file or directory, open 'D:\path\to\file.txt'] {
3737+
errno: -4058,
3738+
code: 'ENOENT',
3739+
syscall: 'open',
3740+
path: 'D:\\path\\to\\file.txt'
3741+
}
3742+
```
3743+
3744+
**4. Using the async/await approach:**
3745+
3746+
Async/await is just syntactic sugar that is meant to augment promises. It provides a synchronous structure to asynchronous code.
3747+
The return value of an async function is a Promise. The await waits for the promise to be resolved or rejected.
3748+
3749+
```js
3750+
const fs = require('fs');
3751+
const util = require('util');
3752+
3753+
const readFile = util.promisify(fs.readFile);
3754+
3755+
const read = async () => {
3756+
try {
3757+
const result = await readFile('/path/to/file.txt');
3758+
console.log(result);
3759+
} catch (err) {
3760+
console.error(err);
3761+
}
3762+
};
3763+
3764+
read();
3765+
```
3766+
3767+
Output:
3768+
3769+
```js
3770+
[Error: ENOENT: no such file or directory, open 'D:\path\to\file.txt'] {
3771+
errno: -4058,
3772+
code: 'ENOENT',
3773+
syscall: 'open',
3774+
path: 'D:\\path\\to\\file.txt'
3775+
}
3776+
```
3777+
3778+
**5. Use Middleware:**
3779+
3780+
It is usually a good idea to build a centralized error-handling component in order to avoid possible code duplications when handling errors. The error-handling component is in charge of making the caught errors understandable by, for example, sending notifications to system admins (if necessary), transferring events to a monitoring service like Sentry.io, and logging them.
3781+
3782+
It is a good decision to employ a customizable logger like winston or morgan. Here is a customized winston logger:
3783+
3784+
**Example:**
3785+
3786+
```js
3787+
const winston = require("winston");
3788+
3789+
const logger = winston.createLogger({
3790+
level: "debug",
3791+
format: winston.format.json(),
3792+
transports: [new winston.transports.Console()],
3793+
});
3794+
3795+
module.exports = logger;
3796+
```
3797+
3798+
```js
3799+
const express = require("express");
3800+
const logger = require("./logger");
3801+
const app = express();
3802+
3803+
app.get("/event", (req, res, next) => {
3804+
try {
3805+
throw new Error("Not User!");
3806+
} catch (error) {
3807+
logger.error("Events Error: Unauthenticated user");
3808+
res.status(500).send("Error!");
3809+
}
3810+
});
3811+
3812+
app.listen(3000, () => {
3813+
logger.info("Server Listening On Port 3000");
3814+
});
3815+
```
3816+
3817+
<div align="right">
3818+
<b><a href="#table-of-contents">↥ back to top</a></b>
3819+
</div>
3820+
36203821
#### Q. How would you handle errors for async code in Node.js?
36213822
#### Q. How to solve "Process out of Memory Exception" in Node.js?
36223823
#### Q. What are the types of memory leaks in node.js

0 commit comments

Comments
 (0)