Exception Handling in Node.js - GeeksforGeeks

16 Feb, 2022
The exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. This are the different methods which can be used for exception handling in Node.js:  
Exception handling in synchronous code:If an error occurs in a synchronous code, return the error. Example:  
javascript
// Write Javascript code here// Define divider as a synchronous functionvar divideSync = function(x, y) {    // if error condition?    if ( y === 0 ) {        // "throw" the error safely by returning it        return new Error("Can't divide by zero")    }    else {        // no error occurred, continue on        return x/y    }} // Divide 9/3var result = divideSync(9, 3)// did an error occur?if ( result instanceof Error ) {    // handle the error safely    console.log("9/3=err", result)}else {    // no error occurred, continue on    console.log("9/3="+result)} // Divide 9/0result = divideSync(9, 0)// did an error occur?if ( result instanceof Error ) {    // handle the error safely    console.log("9/0=err", result)}else {    // no error occurred, continue on    console.log("9/0="+result)}
Output:  
Exception handling in callback-based( asynchronous) code: In callback-based code, the one of the argument of the callback is err. If an error happens err is the error, if an error doesn’t happen then err is null. The err argument can be followed any number of other arguments. Example:  
javascript
// Write Javascript code herevar divide = function(x, y, next) {    // if error condition?    if ( y === 0 ) {        // "throw" the error safely by calling the completion callback        // with the first argument being the error        next(new Error("Can't divide by zero"))    }    else {        // no error occurred, continue on        next(null, x/y)    }} divide(9, 3, function(err, result){    // did an error occur?    if ( err ) {        // handle the error safely        console.log("9/3=err", err)    }    else {        // no error occurred, continue on        console.log("9/3="+result)    }}) divide(9, 0, function(err, result){    // did an error occur?    if ( err ) {        // handle the error safely        console.log("9/0=err", err)    }    else {        // no error occurred, continue on        console.log("9/0="+result)    }})
Output:  
Exception handling in eventful code:In an eventful code, the error may happen anywhere. So instead of throwing the error, fire the error event instead. Example:  
javascript
// Write Javascript code here// Definite our Divider Event Emittervar events = require("events")var Divider = function(){    events.EventEmitter.call(this)}require('util').inherits(Divider, events.EventEmitter) // Add the divide functionDivider.prototype.divide = function(x, y){    // if error condition?    if ( y === 0 ) {        // "throw" the error safely by emitting it        var err = new Error("Can't divide by zero")        this.emit("error", err)    }    else {        // no error occurred, continue on        this.emit("divided", x, y, x/y)    }     // Chain    return this;} // Create our divider and listen for errorsvar divider = new Divider()divider.on('error', function(err){    // handle the error safely    console.log(err)})divider.on('divided', function(x, y, result){    console.log(x+"/"+y+"="+result)}) // Dividedivider.divide(9, 3).divide(9, 0)
Output:  
 
Akanksha_Rai
sagar0719kumar
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript