Home>Article>Web Front-end> A brief analysis of the error handling middleware of Express in Node

A brief analysis of the error handling middleware of Express in Node

青灯夜游
青灯夜游 forward
2022-04-06 20:02:30 3058browse

This article will take you to understand the error handling middleware of Express inNode, and introduce the method of defining error handling middleware and using it with async/await. I hope it will be helpful to everyone!

A brief analysis of the error handling middleware of Express in Node

Express's error handling middlewarehelps you handle errors without repeating the same work. Assuming you handle errors directly in Express route 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 will work fine, however, what if there are hundreds of interfaces, then the error handling logic will become unmaintainable because it is repeated Hundreds of times.

Define error handling middleware

Express is divided into different types according to the number of parameters used by the middleware function. The middleware function that accepts 4 parameters is defined asError handling middlewareand will only be called when an error occurs.

const app = require('express')() app.get('*', function routeHandler() { // 此中间件抛出一个错误,Express 将直接转到下一个错误处理程序 throw new Error('Oops!') }) app.get('*', (req, res, next) => { // 此中间件不是错误处理程序(只有3个参数),Express 将跳过它,因为之前的中间件中存在错误 console.log('这里不会打印') }) // 您的函数必须接受 4 个参数,以便 Express 将其视为错误处理中间件。 app.use((err, req, res, next) => { res.status(500).json({ message: err.message }) })

Express will automatically handle synchronization errors for you, such as therouteHandler()method above. But Express doesn't handle asynchronous errors. If an asynchronous error occurs,next()needs to be called.

const app = require('express')() app.get('*', (req, res, next) => { // next() 方法告诉 Express 转到链中的下一个中间件。 // Express 不处理异步错误,因此您需要通过调用 next() 来报告错误。 setImmediate(() => { next(new Error('Oops')) }) }) app.use((err, req, res, next) => { res.status(500).json({ message: err.message }) })

Remember that Express middleware is executed sequentially. You should define error handlers last, after all other middleware. Otherwise, your error handler will not be called:

Used withasync/await

Express cannot catch exceptions forpromise, Express was written before ES6 and there was no good solution for how to handleasync/awaitit threw.

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

const app = require('express')() app.get('*', (req, res, next) => { // 报告异步错误必须通过 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 wrap or use an existing library to capture.

First, we simply encapsulate a function to connectasync/awaitwith Express error handling middleware.

Note: Async functions return Promise, so you need to make sure tocatch()all errors and pass them tonext().

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 third-party librariesexpress-async-errors, a simple ES6 async/await support hack:

require('express-async-errors') app.get('*', async (req, res, next) => { await new Promise((resolve) => setTimeout(() => resolve(), 50)) throw new Error('woops') })

Finally

Express error handling middleware allows you to handle errors in a way that maximizes separation of concerns. You don't need to handle errors in your business logic, or eventry/catchif you useasync/await. These errors will appear in your error handler, which can then decide how to respond to the request. Make sure to take advantage of this powerful feature in your next Express app!

For more node-related knowledge, please visit:nodejs tutorial!

The above is the detailed content of A brief analysis of the error handling middleware of Express in Node. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete