起因:想给网站配置自定义404模板,但是网站引用think-trace
中间件模板不够灵活,于是便从项目中取消。think-trace
中含有error的处理方法,能够过滤一些错误,需要继续使用,通过编写自定义中间件,抽取think-trace
有用部分。
中间件
1.编写中间件
const helper = require('think-helper');
module.exports = (opts, app) => {
return (ctx, next) => {
let errorCallback;
if (opts && helper.isFunction(opts.error)) {
errorCallback = opts.error;
} else {
errorCallback = console.error.bind(console);
}
return next().catch((err) => {
if (errorCallback(err, ctx) === false) {
return Promise.resolve();
}
throw err;
});
};
};
2.注册中间件
{
handle: 'error',
options: {
error(err) {
if (think.isPrevent(err)) {
return false;
}
console.error(err);
},
},
},
Comments