@haensl/koa-error-middleware

1.0.1 • Public • Published

koa-error-middleware

Koa error logging middleware using iso-log.

NPM

npm version CircleCI

If downstream middlewares throw, the koa-error-middleware handles those errors gracefully. If the error thrown by a downstream middleware contains a status property (as is the case with Koa's ctx.throw), then the context status code is updated to reflect this, else the context status code is defaulted to 500 (internal server error).

If downstream middlewares throw an error with status lower than 500 and the error is exposed, the error message is set as the response body.

If the context status code ends up equal to or greater than 500 (internal server error), the error middleware logs the request and error using iso-log. This requires the iso-log to be initialized. When doing so the error middlware tries to extrapolate the user id from context, i.e. ctx.userId, and attaches the Koa context to the error.

Installation

Via npm

$ npm install -S @haensl/koa-error-middleware @haensl/iso-log

Via yarn

$ yarn add @haensl/koa-error-middleware @haensl/iso-log

Usage

  1. Install @haensl/koa-error-middleware

  2. Ensure you have iso-log installed and initialized.

  3. Use koa-error-middlware in your projects:

    const Koa = require('koa');
    const errorLog = require('@haensl/koa-error-middleware');
    const log = require('@haensl/iso-log');
    
    // Initialize your app
    const app = new Koa();
    
    // Don't forget to initialize iso-log
    log.init({
      // ...
    });
    
    // Attach error logging middleware
    app.use(errorLog());

Synopsis

The koa-error-middleware is exposed as a function that returns an async Koa middleware:

() => async (ctx, next) => { }

Changelog

Package Sidebar

Install

npm i @haensl/koa-error-middleware

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

6.43 kB

Total Files

4

Last publish

Collaborators

  • haensl