express@4 默认使用 try/catch 捕获错误,所以无法处理异步错误

30 阅读1分钟

如果中间一个 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 ✅ */ })