【发布时间】:2019-03-08 11:36:32
【问题描述】:
我为我的 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,但事实并非如此。
我用谷歌搜索无济于事。请帮忙!
【问题讨论】:
标签: javascript koa