Table of contents
1.
Creating exceptions:
2.
Error objects:
3.
Handling exceptions:
4.
Catching uncaught exceptions:
5.
Exceptions with promises:
6.
Error handling with async/await:
7.
Frequently asked question:
8.
Key Takeaways:
Last Updated: Mar 27, 2024

Error handling in Node.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Creating exceptions:

Expressions are generally created with the usage of the throw keyword. The structure looks like this:

throw value

 

When this line is executed by javascript, normal program flow gets halted, and control gets held by the nearest exception handler. 

The value can be anything in client-side code, including a string, number, or even an object.

Instead, in Node.js, we only throw Error objects and not the strings.

 

Error objects:

An object that persists in the Error object’s instance or extends the Error class refers to the Error object. 

 

 

throw new Error('Ran out of coffee')

 

Or,

class NotEnoughCoffeeError extends Error {
 //...
}
throw new NotEnoughCoffeeError()

 

Handling exceptions:

An exception handling is a try/catch statement. If any exception is raised in the try block in the lines of code, that will be handled by the catch block of a particular try block only.

 

try {
 //lines of code
catch (e) {}

 

Here, “e” is the exception value. Multiple handlers can be added to catch different kinds of errors.

 

Catching uncaught exceptions:

Uncaught exceptions are those that are not handled by the catch block and remain as they are during the program’s execution, then such scenarios will lead to system crash. 

 

process.on('uncaughtException', err => {
 console. error('There was an uncaught error,’ err)
process.exit(1//mandatory (as per the Node.js docs)
})

 

Importing the process core model is not required, as it gets automatically injected. 

 

Exceptions with promises:

Different operations can be chained using promises, and errors are handled at the end.

doSomething1()
.then(doSomething2)
.then(doSomething3)
.catch(err => console.error(err))

 

But the question is, how to know exactly where the error is? You really don’t know right. But, errors can be handled in each function that is being called. In the example given above, errors can be handled in each function call(doSomethingX), and inside the error handler will throw a new error and that will be handled by the catch handler.

 

const doSomething1 = () => {
 //...
 try {
  //...
catch (err) {
  //... handle it locally
  throw new Error(err.message)
}
 //...
}

 

Now, the error handling part can also be done locally, without doing them in function call. This can be done easily by breaking the chain. We can create a function in each then() and process the exception:

 

doSomething1()
.then(() => {
  return doSomething2().catch(err => {
    //Handle error.
    throw err //Break the chain.
  })
})
.then(() => {
  return doSomething3().catch(err => {
    //Handle error.
    throw err //Break the chain.
  })
})
.catch(err => console.error(err))

 

Error handling with async/await:

Using async or await, we can also handle errors. The structure looks like:

 

async function someFunction() {
 try {
  await someOtherFunction()
catch (err) {
  console.error(err.message)
}
}

 

 

 

 

 

 

 

Also see, Difference Between Controller and Restcontroller

Frequently asked question:

  1. Express error handling in Node.js?

 

Error handling is the way to express catches and process errors. It is done both synchronous and asynchronous ways. Express has its own error handler, so we don’t need to write on our own.

2. Await throws an error. Justify the statement.

 

If any promise fails to resolve normally, then await cannot return the result. In such cases, await throws an error.

3. Is node.js a programming language?

 

No, node.js is not a programming language. But, it makes use of javascript which is a programming language. It also helps web developers to play and build web applications.

4. Name some uses of node.js?

 

The uses of node.js are:

  • Server-side programming
  • Deployed for non-blocking
  • Creating and deleting server files.

Key Takeaways:

In this article we have learned error handling in node.js. Error can occur anywhere, but it should be handled properly. Like we have seen above, in a code, there can be many try catch blocks but the error on one particular try will be handled by its catch block only. Failing to do so, will result in a system crash.

Keeping the theoretical knowledge at our fingertips helps us get about half the work done. To gain complete understanding, practice is a must. To gain complete understanding, visit our page.

 

By: Pradipta Choudhury

Live masterclass