I have made a custom error handler for my koa app which works beautifully (except for one sticking point) - using ctx.throw()
means any stacktrace is emitted to the server logs and also any custom error message is sent in the response.
The one problem is that Content-Type
header is text/plain
but I really need it to be 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 }));
});
};
(I thought (statusCode, JSON.stringify({ message }));
might coerce the response into application/json
but it doesn't.
I have googled to no avail. Please help!