Error Handling in Nodejs Express

Tram Ho

Error Handling refers to how Express catches and handles errors that occur synchronously and asynchronously . Express comes with a default Error handler, so you don’t need to write it to get started.

Catching Errors

It is important to ensure that Express catches all errors that occur while route handlers and middleware are run.

Errors occur in synchronous code Đồng bộ within route handlers and middleware does not need to do any extra work. If the synchronous code generates an error, then Express will catch it and handle it. For example:

For errors returned from Bất đồng bộ asynchronous functions called by route handlers and middleware , you must pass them to the next() function, where Express will catch and process them. For example:

Starting with Express 5 , route handlers and middleware return a Promise that will automatically call next(value) when they are reject or gặp lỗi . For example:

If getUserById throws an error or reject , next will be called with the lỗi thrown or the value reject . If no rejected value is reject , next will be called with the default Lỗi object provided by Router Express .

If you pass anything to the next() function (except the string 'route' ), Express treats the current request as an lỗi and will ignore any subsequent route handlers and middleware and go straight to error handling.

If the callback in a string gives no data, only an error, you can simplify this code as follows:

In the above example next is provided as a callback for fs.writeFile , which is called with or without an error. If there is no error, the second handler will be executed, otherwise Express will catch and handle the error.

You must catch errors that occur in asynchronous code called by route handlers or middleware and pass them on to Express for handling. For example:

The above example uses a try...catch block to catch errors in asynchronous code and pass them on to Express . If the try...catch block is omitted, Express will not catch the error because it is not part of the synchronous processing code.

Use promise as an alternative to try...catch blocks or when using functions that return promise . For example:

Since promises automatically catch both synchronous errors and rejected reject , you can simply provide as next the last catch handler and Express will catch the error, since the caught handler provides the error as the first argument .

You can also use a chain of handlers to rely on synchronous error-catching, by reducing the asynchronous code to something small. For example:

The above example uses the common statement from the readFile object. If readFile an error, it passes the error to Express , otherwise you’ll quickly fall back to Global Error Handling synchronous in the next handler in the chain. Then it will try to process the data. If this fails then the Error Handling synchronous will catch it. If you did this processing inside the readFile callback , the application could exit and the Error Handling Express would not run.

Whichever function you use, if you want the Error Handling Express to be called and the application to survive, you must ensure that the Express receives the error.

This paragraph is a bit confusing to explain, but it’s okay if you read this article, you will understand what this paragraph I want to say.

Default Error handler

Express integrates an lỗi handler that handles any errors that may be encountered in the application. This default Middleware function Error Handling is added to the bottom of the Middleware stack.

If you pass an error to next() and you don’t handle it in a custom lỗi handler, it will be handled by the built-in lỗi handler; Errors will be logged to the Client with Stack Trace . Stack Trace is not provided in production environment .

Set the NODE_ENV environment variable to production , to run the app in production environment mode.

When an error is logged, the following information is added to the response :

  • Set res.statusCode from err.status (or err.statusCode ). If this value is outside the 4xx or 5xx range, it will be set to 500.
  • Set res.statusMessage by status code.
  • The body will be the HTML of the status code message when in production , otherwise err.stack .
  • Any headers specified in an err.headers object.

If you call next() with an error after starting the response (for example, if you get an error while passing the response to the Client ), the Express default lỗi handler closes the connection and fails to make the request .

So when you add a custom lỗi handler, you have to delegate to the default Express lỗi handler, once the headers have been sent to the Client :

Note that the default lỗi handler can be triggered if you call next() multiple times with an error in your code, even if a custom middleware Error Handling is available.

Write an Lỗi handler

Define the Middleware function Error Handling in the same way as other Middleware function , except that the function Error Handling take four arguments instead of three. For example: (err, req, res, next) .

You must declare the middleware Error Handling last, after other calls to app.use() and Router ; For example:

The Response from within a Middleware function can be in any format, such as an HTML error page, a simple message, or a string JSON .

For organizational (and higher-level framework ), you can define a Middleware function Error Handling , the same way you would work with regular Middleware function . For example, to define an lỗi handler for request made using XHR and request without:

In this example, the general logErrors can log request and stderr error information, for example:

Also in this example, the clientErrorHandler is defined as follows: The error is explicitly passed to the next error.

Note that when not calling next in an Error Handling function, it is your responsibility to write (and finish) the response . Otherwise, those request will ” treo ” and gradually overflow the memory.

The implementation function ” catch-all ” named errorHandler like this (example):

If you have a Route handler with multiple callback , you can use the route parameter to pass to the next route handler. For example:

In this example, the getPaidContent handler will be ignored but any handlers left in the app that handle the Route for /a_route_behind_paywall will continue to be executed.

Calls to next() and next(err) indicate that the current handler has completed and at what stage. next(err) will ignore all remaining handlers in the chain except those set to Error Handling as described above.

Roudup

As always, I hope you enjoyed this article and learned something new.

Thank you and see you in the next posts!

If you find this blog interesting, please give me a like and subscribe to support me. Thank you.

Ref

Share the news now

Source : Viblo