1,在接口中先抛出错误
const { ctx } = this;
ctx.throw(500, '故意出错')
//ctx.body = 'hi, egg';
console.log(ctx.request.body)
ctx.body = ctx.request.body
2,在app文件下创建middleware文件夹,同时创建一个error_handler.js的文件
// app/middleware/error_handler.js
module.exports = (option, app) => {
return async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
// 从 error 对象上读出各个属性,设置到响应中
ctx.body = { error };
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
};
};
3,在config.default.js中配置
config.middleware = ['errorHandler'];
config.errorHandler = {
// 通用配置(以下是重点)
// enable:true, // 控制中间件是否开启。
match:'/user/list', // 设置只有符合某些规则的请求才会经过这个中间件(匹配路由)
//ignore:'/shop' // 设置符合某些规则的请求不经过这个中间件。
/**
注意:
1. match 和 ignore 不允许同时配置
**/
// match 和 ignore 支持多种类型的配置方式:字符串、正则、函数(推荐)
// match(ctx) {
// // 只有 ios 设备才开启
// const reg = /iphone|ipad|ipod/i;
// return reg.test(ctx.get('user-agent'));
// },
};