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:
If an error occurs in a synchronous code, return the error.
Example:
// Write Javascript code here
// Define divider as a syncrhonous function
var 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/3
var 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/0
result = 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:
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:
// Write Javascript code here
var 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: