koa-better-error-handler
A better error-handler for Koa v2+, built for CrocodileJS. Makes ctx.throw
beautiful again :sparkles:!
Index
Features
- Uses Boom for making error messages beautiful (see User Friendly Responses below)
- Simply a better error handler (doesn't remove all headers like the built-in one does)
- Doesn't make all status codes 500 (like the built-in Koa error handler does)
- Supports Flash messages and preservation of newly set session object
- Fixes annoying redirect issue where flash messages were lost upon an error being thrown
- Makes
ctx.throw
beautiful messages (e.g. ctx.throw(404)
will output a beautiful error object :hibiscus:) - Supports
text/html
, application/json
, and text
response types
Install
npm install --save koa-better-error-handler
Usage
API
No support for sessions, cookies, or flash messaging:
import errorHandler from 'koa-better-error-handler';
import Koa from 'koa';
import Router from 'koa-router';
const app = new Koa();
app.context.onerror = errorHandler;
const router = new Router();
router.get('/404', ctx => ctx.throw(404));
router.get('/500', ctx => ctx.throw(500));
app.use(router.routes());
app.use(async (ctx, next) => {
try {
await next();
if (ctx.status === 404)
ctx.throw(404);
} catch (err) {
ctx.throw(err);
ctx.app.emit('error', err, ctx);
}
});
app.listen(3000);
console.log('listening on port 3000');
Web App
Built-in support for sessions, cookies, and flash messaging:
import errorHandler from 'koa-better-error-handler';
import Koa from 'koa';
import redis from 'redis';
import RedisStore from 'koa-redis';
import session from 'koa-generic-session';
import flash from 'koa-connect-flash';
import convert from 'koa-convert';
import Router from 'koa-router';
const app = new Koa();
app.keys = [ 'foo', 'bar' ];
const redisClient = redis.createClient();
redisClient.on('connect', () => app.emit('log', 'info', 'redis connected'));
redisClient.on('error', err => app.emit('error', err));
const redisStore = new RedisStore({
client: redisClient
});
app.use(convert(session({
store: redisStore
})));
app.use(convert(flash()));
app.context.onerror = errorHandler;
const router = new Router();
router.get('/404', ctx => ctx.throw(404));
router.get('/500', ctx => ctx.throw(500));
app.use(router.routes());
app.use(async (ctx, next) => {
try {
await next();
if (ctx.status === 404)
ctx.throw(404);
} catch (err) {
ctx.throw(err);
ctx.app.emit('error', err, ctx);
}
});
app.listen(3000);
console.log('listening on port 3000');
User-Friendly Responses
Example Request:
curl -H "Accept: application/json" http://localhost/some-page-does-not-exist
Example Response:
{
"statusCode": 404,
"error": "Not Found",
"message":"Not Found"
}
License
MIT