nodejs-koa(四)中间件捕获异常
这里我简单弄一下,在app.js中加入,写在路由的前面
/**
* 捕获异常
*/
app.use(async (ctx,next)=>{
try {
await next(); //必须,程序在这里暂停并将控制传递给定义的下一个中间件,最后再回过头执行
if(ctx.status == 404){
ctx.body = '404';
}else if(ctx.status == 405){
ctx.body = '405';
}
}catch (error) { //其他异常
console.log(error);
}
})
require("./lib/RouterLib").init(app); //初始化路由,app为 new Koa对象
app.listen(config.port); // 监听配置中的3000端口