- Notifications
You must be signed in to change notification settings - Fork9
A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)
License
ladjs/koa-better-error-handler
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A better error-handler forLad andKoa. Makes
ctx.throwawesome (best used withkoa-404-handler)
- Detects Node.js DNS errors (e.g.
ETIMEOUTandEBADFAMILY) and sends 408 Client Timeout error - Detects Mongoose errors and sends 408 Client Timeout error
- Detects common programmer mistakes by detecting errors of TypeError, SyntaxError, ReferenceError, RangeError, URIError, and EvalError and yields generic "Internal Server Error" (only applies to production mode)
- Detects Redis errors (e.g. ioredis' MaxRetriesPerRequestError) and sends 408 Client Timeout error
- UsesBoom for making error messages beautiful (seeUser Friendly Responses below)
- Simply a better error handler (doesn't remove all headerslike 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
- SupportsHTML Error Lists using
<ul>for Mongoose validation errors with more than one message - Makes
ctx.throwbeautiful messages (e.g.ctx.throw(404)will output a beautiful error object 🌺) - Supports
text/html,application/json, andtextresponse types - Supports and recommends use ofmongoose-beautiful-unique-validation
npm install --save koa-better-error-handler
You should probably be using this in combination withkoa-404-handler too!
The package exports a function which accepts four arguments (in order):
cookiesKey- defaults tofalselogger- defaults toconsoleuseCtxLogger- defaults totruestringify- defaults tofast-safe-stringify(you can also useJSON.stringifyor another option here if preferred)
If you pass acookiesKey then support for sessions will be added. You should always set this argument's value if you are using cookies and sessions (e.g. web server).
We recommend to useCabin for yourlogger and also you should use its middleware too, as it will auto-populatectx.logger for you to make context-based logs easy.
Note that this package only supportskoa-generic-session, and does not yet supportkoa-session-store (see the code inindex.js for more insight, pull requests are welcome).
No support for sessions, cookies, or flash messaging:
consterrorHandler=require('koa-better-error-handler');constKoa=require('koa');constRouter=require('koa-router');constkoa404Handler=require('koa-404-handler');// initialize our appconstapp=newKoa();// override koa's undocumented error handlerapp.context.onerror=errorHandler();// specify that this is our apiapp.context.api=true;// use koa-404-handlerapp.use(koa404Handler);// set up some routesconstrouter=newRouter();// throw an error anywhere you want!router.get('/404',ctx=>ctx.throw(404));router.get('/500',ctx=>ctx.throw(500));// initialize routes on the appapp.use(router.routes());// start the serverapp.listen(3000);console.log('listening on port 3000');
Built-in support for sessions, cookies, and flash messaging:
consterrorHandler=require('koa-better-error-handler');constKoa=require('koa');constredis=require('redis');constRedisStore=require('koa-redis');constsession=require('koa-generic-session');constflash=require('koa-connect-flash');constconvert=require('koa-convert');constRouter=require('koa-router');constkoa404Handler=require('koa-404-handler');// initialize our appconstapp=newKoa();// define keys used for signing cookiesapp.keys=['foo','bar'];// initialize redis storeconstredisClient=redis.createClient();redisClient.on('connect',()=>app.emit('log','info','redis connected'));redisClient.on('error',err=>app.emit('error',err));// define our storageconstredisStore=newRedisStore({client:redisClient});// add sessions to our appconstcookiesKey='lad.sid';app.use(convert(session({key:cookiesKey,store:redisStore})));// add support for flash messages (e.g. `req.flash('error', 'Oops!')`)app.use(convert(flash()));// override koa's undocumented error handlerapp.context.onerror=errorHandler(cookiesKey);// use koa-404-handlerapp.use(koa404Handler);// set up some routesconstrouter=newRouter();// throw an error anywhere you want!router.get('/404',ctx=>ctx.throw(404));router.get('/500',ctx=>ctx.throw(500));// initialize routes on the appapp.use(router.routes());// start the serverapp.listen(3000);console.log('listening on port 3000');
Example Request:
curl -H"Accept: application/json" http://localhost/some-page-does-not-existExample Response:
{"statusCode":404,"error":"Not Found","message":"Not Found"}As of v3.0.5, you can prevent an error from being automatically translated by setting the error property ofno_translate to have a value oftrue:
functionmiddleware(ctx){consterr=Boom.badRequest('Uh oh!');err.no_translate=true;// <----ctx.throw(err);}
If you specifyapp.context.api = true or setctx.api = true, and if a Mongoose validation error message occurs that has more than one message (e.g. multiple fields were invalid) – thenerr.message will be joined by a comma instead of by<li>.
Therefore if youDO want your API error messages to return HTML formatted error lists for Mongoose validation, then setapp.context.api = false,ctx.api = false, or simply make sure to not set them before using this error handler.
try{// trigger manual validation// (this allows us to have a 400 error code instead of 500)awaitcompany.validate();}catch(err){ctx.throw(Boom.badRequest(err));}
With error lists:
{"statusCode":400,"error":"Bad Request","message":"<ul class=\"text-left mb-0\"><li>Path `company_logo` is required.</li><li>Gig description must be 100-300 characters.</li></ul>"}Without error lists:
{"statusCode":400,"error":"Bad Request","message":"Path `company_logo` is required., Gig description must be 100-300 characters."}By default ifctx.api is true, thenhtml-to-text will be invoked upon theerr.message, thus converting all the HTML markup into text format.
You can also specify a base URI in the environment variable for rendering asprocess.env.ERROR_HANDLER_BASE_URL, e.g.ERROR_HANDLER_BASE_URL=https://example.com (omit trailing slash), and any HTML links such as<a href="/foo/bar/baz">Click here</a> will be converted to[Click here][1] with a[1] link appended ofhttps://example.com/foo/bar/baz.
About
A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.