Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)

License

NotificationsYou must be signed in to change notification settings

ladjs/koa-better-error-handler

build statuscode stylestyled with prettiermade with lasslicense

A better error-handler forLad andKoa. Makesctx.throw awesome (best used withkoa-404-handler)

Index

Features

  • Detects Node.js DNS errors (e.g.ETIMEOUT andEBADFAMILY) 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
  • Makesctx.throw beautiful messages (e.g.ctx.throw(404) will output a beautiful error object 🌺)
  • Supportstext/html,application/json, andtext response types
  • Supports and recommends use ofmongoose-beautiful-unique-validation

Install

npm install --save koa-better-error-handler

Usage

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 tofalse
  • logger - defaults toconsole
  • useCtxLogger - defaults totrue
  • stringify - defaults tofast-safe-stringify (you can also useJSON.stringify or 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).

API

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');

Web App

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');

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"}

Prevent Errors From Being Automatically Translated

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);}

HTML Error Lists

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."}

API Friendly Messages

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.

License

MIT ©Nick Baugh

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

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp