try {} catch (error){ next(error) }
Promise.then().catch(error => next(error))
// 可以简写成,next 参数与 catch 一致
Promise.then().catch(next)
404 error
异常处理中间件,必须放在 router 的最后面
这样才能做到兜底
const express = requre(express)
const app = express()
app.get('/demo',(req.res)=>{
thorw new Error('测试异常功能')
})
funtion error_handler_middleware(err,req,res,next){
if(err){
res.status(5000).json({
message:'服务器异常'
})
}
}
app.use(error_handler_middleware)
app.listen(3000,()=>{
})
promise里的catch需要一个error参数的函数,而处理异常时next刚好是一个参数为error的函数
当发现在middleware里有异常时,通过next(error)传到下一层
处理不存在的路由,放在最外层
中间件处理异常细节
中间件处理异常,放在所有链式之后
不错不错@@