如果中间一个 api 使用了 async,则该错误处理不会被捕获到
正常工作:
app.post('/user/login', (req, res) => { /* somthing wrong! */})
app.use((err, req, res, next) => { /* succeed catch error*/ })
无法工作、程序奔溃:
app.post('/user/login', async (req, res) => { /* somthing wrong! */})
app.use((err, req, res, next) => { /* can't catch error ❌ */ })
想要解决,只能在每一个异步函数中手动处理异步错误。由于该功能很常见,所以可以自行封装成一个模块
export const asyncHandler = fn => (...args) => {
const fnReturn = fn(...args)
const next = args[args.length - 1]
return Promise
.resolve(fnReturn)
.catch(next)
}
app.post('/user/login', asyncHandler(
async (req, res) => { /* somthing wrong! */}
))
app.use((err, req, res, next) => { /* can catch error ✅ */ })
或者你可以之间使用 express@5 版本,最新版本中不需要自己添加 asyncHandler 函数
npm install "express@>=5.0.0-beta.1" --save
# 由于还是测试版本,所以需要安装 beta
下面是一个简单的案例,给纯新手玩玩:
const express = require('express')
const app = express()
app.get('/user/login', async (req, res) => {
if (req) {
throw new Error('sdf')
}
})
app.use((err, req, res, next) => {
res.status(500).send('Something broke!')
})
app.listen(3001, () => console.log(`listen 3001`))