You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+202-1Lines changed: 202 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -3616,7 +3616,208 @@ Few events are :
3616
3616
<b><a href="#table-of-contents">↥ back to top</a></b>
3617
3617
</div>
3618
3618
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
+
<divalign="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
+
functionsquare(num) {
3662
+
if (typeof num !=="number") {
3663
+
thrownewTypeError(`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
+
functionsquare(num) {
3687
+
returnnewPromise((resolve, reject) => {
3688
+
setTimeout(() => {
3689
+
if (typeof num !=="number") {
3690
+
reject(newTypeError(`Expected number but got: ${typeof num}`));
3691
+
}
3692
+
3693
+
constresult= 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.
[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
+
constfs=require('fs');
3751
+
constutil=require('util');
3752
+
3753
+
constreadFile=util.promisify(fs.readFile);
3754
+
3755
+
constread=async () => {
3756
+
try {
3757
+
constresult=awaitreadFile('/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:
0 commit comments