Coder Social home page Coder Social logo

ladjs / koa-better-error-handler Goto Github PK

View Code? Open in Web Editor NEW
52.0 7.0 9.0 880 KB

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

Home Page: https://lad.js.org

License: MIT License

HTML 12.97% JavaScript 86.24% Shell 0.79%
node error handler error-handling error-handler flash-messages flash messages boom validation

koa-better-error-handler's Introduction

koa-better-error-handler

build status code style styled with prettier made with lass license

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

Index

Features

  • Detects Node.js DNS errors (e.g. ETIMEOUT and EBADFAMILY) 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
  • 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
  • Supports HTML Error Lists using <ul> for Mongoose validation errors with more than one message
  • Makes ctx.throw beautiful messages (e.g. ctx.throw(404) will output a beautiful error object ๐ŸŒบ)
  • Supports text/html, application/json, and text response types
  • Supports and recommends use of mongoose-beautiful-unique-validation

Install

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

Usage

You should probably be using this in combination with koa-404-handler too!

The package exports a function which accepts four arguments (in order):

  • cookiesKey - defaults to false
  • logger - defaults to console
  • useCtxLogger - defaults to true
  • stringify - defaults to fast-safe-stringify (you can also use JSON.stringify or another option here if preferred)

If you pass a cookiesKey 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 use Cabin for your logger and also you should use its middleware too, as it will auto-populate ctx.logger for you to make context-based logs easy.

Note that this package only supports koa-generic-session, and does not yet support koa-session-store (see the code in index.js for more insight, pull requests are welcome).

API

No support for sessions, cookies, or flash messaging:

const errorHandler = require('koa-better-error-handler');
const Koa = require('koa');
const Router = require('koa-router');
const koa404Handler = require('koa-404-handler');

// initialize our app
const app = new Koa();

// override koa's undocumented error handler
app.context.onerror = errorHandler();

// specify that this is our api
app.context.api = true;

// use koa-404-handler
app.use(koa404Handler);

// set up some routes
const router = new Router();

// throw an error anywhere you want!
router.get('/404', ctx => ctx.throw(404));
router.get('/500', ctx => ctx.throw(500));

// initialize routes on the app
app.use(router.routes());

// start the server
app.listen(3000);
console.log('listening on port 3000');

Web App

Built-in support for sessions, cookies, and flash messaging:

const errorHandler = require('koa-better-error-handler');
const Koa = require('koa');
const redis = require('redis');
const RedisStore = require('koa-redis');
const session = require('koa-generic-session');
const flash = require('koa-connect-flash');
const convert = require('koa-convert');
const Router = require('koa-router');
const koa404Handler = require('koa-404-handler');

// initialize our app
const app = new Koa();

// define keys used for signing cookies
app.keys = ['foo', 'bar'];

// initialize redis store
const redisClient = redis.createClient();
redisClient.on('connect', () => app.emit('log', 'info', 'redis connected'));
redisClient.on('error', err => app.emit('error', err));

// define our storage
const redisStore = new RedisStore({
  client: redisClient
});

// add sessions to our app
const cookiesKey = '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 handler
app.context.onerror = errorHandler(cookiesKey);

// use koa-404-handler
app.use(koa404Handler);

// set up some routes
const router = new Router();

// throw an error anywhere you want!
router.get('/404', ctx => ctx.throw(404));
router.get('/500', ctx => ctx.throw(500));

// initialize routes on the app
app.use(router.routes());

// start the server
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"
}

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 of no_translate to have a value of true:

function middleware(ctx) {
  const err = Boom.badRequest('Uh oh!');
  err.no_translate = true; // <----
  ctx.throw(err);
}

HTML Error Lists

If you specify app.context.api = true or set ctx.api = true, and if a Mongoose validation error message occurs that has more than one message (e.g. multiple fields were invalid) โ€“ then err.message will be joined by a comma instead of by <li>.

Therefore if you DO want your API error messages to return HTML formatted error lists for Mongoose validation, then set app.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)
  await company.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 if ctx.api is true, then html-to-text will be invoked upon the err.message, thus converting all the HTML markup into text format.

You can also specify a base URI in the environment variable for rendering as process.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 of https://example.com/foo/bar/baz.

License

MIT ยฉ Nick Baugh

koa-better-error-handler's People

Contributors

3imed-jaberi avatar niftylettuce avatar pablopunk avatar shaunwarman avatar titanism avatar williamboman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-better-error-handler's Issues

v1.1.2 runtime error

Error: Cannot find module 'babel-runtime/regenerator'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object. (D:\home\site\wwwroot\node_modules\koa-better-error-handler\lib\index.js:7:20)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)

Possibility to enumerate errors.

What I would like is:

ctx.throw(
  new Boom('Trying to create an already existing element', { statusCode: 409, decorate: { code: 101 } })
)

Important part here being { decorate: { code: 101 } }
If that information would be forwarded to the JSON produced from koa, the user could get a numeric reference to that error.

That is useful for a number of purposes

As i seen through the code, this line seems to be my enemy: index.js#L91
since it makes a new Boom error, it cannot use the object I created before

Mongoose validation error code

Hello, I'm having some trouble with error codes when a mongoose validation error occurs. I get a different error message, so it seems the handler is working, but it always throws status code 500 instead of 400 like it's shown in the documentation.

I am using mongoose 5.0.13 and koa-better-error-handler 1.3.5.

Is there anything else that needs to be done that's not mentioned in the usage guide?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.