我已经为我的koa应用程序制作了一个自定义错误处理程序,该程序处理得很好(除了一个棘手的问题)-使用ctx.throw()
意味着将任何堆栈跟踪信息发送到服务器日志,并且还将在响应。
一个 问题是Content-Type
标头是text/plain
,但我真的需要它是application/json
。
app.js
:
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import logger from 'koa-morgan';
import authentication from './middleware/authentication';
import config from './config';
import errorHandler from './middleware/error-handler';
import notificationsRoutes from './routes/notifications';
const app = new Koa();
app.use(errorHandler);
app.use(bodyParser());
app.use(logger(config.logLevel));
app.use(authentication);
app.use(notificationsRoutes.routes());
export default app;
error-handler.js
:
export default async (ctx, next) => {
return next().catch(({ statusCode, message }) => {
ctx.throw(statusCode, JSON.stringify({ message }));
});
};
(我以为(statusCode, JSON.stringify({ message }));
可以将响应强制为application/json
,但事实并非如此。
我用Google搜索无济于事。请帮忙!
答案 0 :(得分:0)
设法修改error-handler
以产生所需的结果。效果非常好-堆栈跟踪被发送到服务器日志,并且该消息的第一行成为响应正文中的message
。某些人可能会将后者视为不利因素,但这取决于您的追求。
error-handler.js
:
export default async (ctx, next) => {
return next().catch(err => {
const { statusCode, message } = err;
ctx.type = 'json';
ctx.status = statusCode || 500;
ctx.body = {
status: 'error',
message
};
ctx.app.emit('error', err, ctx);
});
};
找到了这个并将其用作参考:https://github.com/koajs/examples/blob/master/errors/app.js
值得一提的是,此自定义错误-ServerError.js
-已在应用中使用;这就是使用时{{1}提供ctx.status = statusCode || 500
-statusCode
的原因,但是对于抛出的非自定义错误,ServerError
会以{{ 1}},因此需要statusCode
。
error-handler.js
:
undefined
(用法:|| 500
)
您的任何中间件中都没有任何ServerError.js
块,并且错误将一直传播到export class ServerError extends Error {
constructor(statusCode, message) {
super(message);
this.statusCode = statusCode;
}
}
中最重要的throw new ServerError(400, 'my informative error message');
中间件(这是您想要的)发生)。
koa中的自定义错误处理似乎会产生许多不同的见解,但这似乎对我们目前来说很有效。