Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to define the error handling middleware of Express in Node

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to define the error handling middleware of Express in Node". In daily operation, I believe that many people have doubts about how to define the error handling middleware of Express in Node. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to define the error handling middleware of Express in Node". Next, please follow the editor to study!

Express's error handling middleware can help you handle errors without having to repeat the same work. Suppose you handle errors directly in the Express routing handler:

App.put ('/ user/:id', async (req, res) = > {let user try {user = await User.findOneAndUpdate ({_ id: req.params.id}, req.body)} catch (err) {return res.status (err.status | | 500). Json ({message: err.message})} return res.json ({user})})

The above code works fine, but if there are hundreds of interfaces, the error handling logic becomes unmaintainable because it is repeated hundreds of times.

Define error handling middleware

Express is divided into different types according to the number of parameters taken by the middleware function. A middleware function that accepts four parameters is defined as error handling middleware and is called only when an error occurs.

Const app = require ('express') () app.get (' *', function routeHandler () {/ / this middleware throws an error, Express will go directly to the next error handler throw new Error ('Oopshandlers)}) app.get (' *', (req, res, next) = > {/ / this middleware is not an error handler (only 3 parameters), Express will skip it Because there is an error in the previous middleware console.log ('not printed here)}) / / your function must accept four parameters so that Express can treat it as error-handling middleware. App.use ((err, req, res, next) = > {res.status (500) .json ({message: err.message})})

Express will automatically handle synchronization errors for you, such as the routeHandler () method above. But Express does not handle asynchronous errors. If an asynchronous error occurs, you need to call next ().

The const app = require ('express') () app.get (' *', (req, res, next) = > {/ / next () method tells Express to go to the next middleware in the chain. / / Express does not handle asynchronous errors, so you need to report errors by calling next (). SetImmediate (() = > {next (new Error ('Oops'))})}) app.use ((err, req, res, next) = > {res.status (500) .json ({message: err.message})})

Keep in mind that Express middleware is executed sequentially. You should finally define an error handler after all other middleware. Otherwise, your error handler will not be called:

Use with async/await

Express cannot catch promise exceptions. Express was written before ES6, and there is no good solution to how to handle async/await throwing.

For example, the following server will never successfully send a HTTP response because the Promise reject will never be processed:

Const app = require ('express') () app.get (' *', (req, res, next) = > {/ / Asynchronous errors must be reported through next () return new Promise ((resolve, reject) = > {setImmediate (() = > reject (new Error ('woops'))}) .catch (next)}) app.use ((error, req, res) Next) = > {console.log ('will not print') res.json ({message: error.message})}) app.listen (3000)

We can encapsulate or use an existing library for capture.

First of all, let's simply encapsulate a function that connects async/await to Express error handling middleware.

Note: asynchronous functions return Promise, so you need to make sure that catch () all errors and pass them to next ().

Function wrapAsync (fn) {return function (req, res, next) {fn (req, res, next). Catch (next)}} app.get ('*', wrapAsync (async (req, res) = > {await new Promise (resolve = > setTimeout () = > resolve (), 50) / / Async error! Throw new Error ('woops')}))

Using the third-party library express-async-errors, a simple ES6 async/await supports hack:

Require ('express-async-errors') app.get (' *', async (req, res, next) = > {await new Promise ((resolve) = > setTimeout (() = > resolve (), 50)) throw new Error ('woops')}) at this point, the study on "how to define Express error handling middleware in Node" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report