GithubHelp home page GithubHelp logo

json-error's Introduction

Koa JSON Error

NPM version Build status Test coverage Dependency Status License Downloads

Error handler for pure Koa >=2.0.0 JSON apps where showing the stack trace is cool!

npm install --save koa-json-error

Versions >=3.0.0 support Koa ^2.0.0. For earlier versions of Koa, please use previous releases.

Requirements

  • node >=6.0.0
  • koa >=2.2.0

Starting from 3.2.0, this package supports node >=6.0.0 to match Koa requirements.

API

'use strict';
const koa = require('koa');
const error = require('koa-json-error')

let app = new Koa();
app.use(error())

If you don't really feel that showing the stack trace is that cool, you can customize the way errors are shown on responses. There's a basic and more advanced, granular approach to this.

Basic usage

You can provide a single formatter function as an argument on middleware initialization. It receives the original raised error and it is expected to return a formatted response.

Here's a simple example:

'use strict';
const koa = require('koa');
const error = require('koa-json-error')

function formatError(err) {
    return {
        // Copy some attributes from
        // the original error
        status: err.status,
        message: err.message,

        // ...or add some custom ones
        success: false,
        reason: 'Unexpected'
    }
}

let app = new Koa();
app.use(error(formatError));

This basic configuration is essentially the same (and serves as a shorthand for) the following:

'use strict';
let app = new Koa();
app.use(error({
    preFormat: null,
    format: formatError
}));

See section below.

Advanced usage

You can also customize errors on responses through a series of three formatter functions, specified in an options object. They receive the raw error object and return a formatted response. This gives you fine-grained control over the final output and allows for different formats on various environments.

You may pass in the options object as argument to the middleware. These are the available settings.

options.preFormat (Function)

Perform some task before calling options.format. Must be a function with the original err as its only argument.

Defaults to:

(err) => Object.assign({}, err)

Which sets all enumerable properties of err onto the formatted object.

options.format (Function)

Runs inmediatly after options.preFormat. It receives two arguments: the original err and the output of options.preFormat. It should return a newly formatted error.

Defaults to adding the following non-enumerable properties to the output:

const DEFAULT_PROPERTIES = [
  'name',
  'message',
  'stack',
  'type'
];

It also defines a status property like so:

obj.status = err.status || err.statusCode || 500;

options.postFormat (Function)

Runs inmediatly after options.format. It receives two arguments: the original err and the output of options.format. It should return a newly formatted error.

The default is a no-op (final output is defined by options.format).

This option is useful when you want to preserve the default functionality and extend it in some way.

For example,

'use strict';
const _ = require('lodash');
const koa = require('koa');
const error = require('koa-json-error')

let options = {
    // Avoid showing the stacktrace in 'production' env
    postFormat: (e, obj) => process.env.NODE_ENV === 'production' ? _.omit(obj, 'stack') : obj
};
let app = new Koa();
app.use(error(options));

Modifying the error inside the *format functions will mutate the original object. Be aware of that if any other Koa middleware runs after this one.

json-error's People

Contributors

greenkeeperio-bot avatar jonathanong avatar nfantone 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  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

json-error's Issues

Using this middleware disables Koa's `error` event handler

I use json-error like the this:

...
koa.use(error({
        preFormat: null,
        format: (error) => {
            const {status, message, code, detail} = error;
            return {
                status,
                message,
                code,
                detail
            }
        }
    }));
...

and it works as expected. However, I noticed recently that my error event handler is now ignored:

koa.on('error', (error, ctx) => {
        // this never fires on error anymore  
        if (!error.status || error.status === 500) {
            logger.error(error.stack);
        }
        ctx.message = error.message;
        logger.error(`!! [${ctx.state.id}] ${error.status}`, error.message);
    });

If I remove json-error middleware, the error event handler starts to work again.

I guess I can move my handler to json-error format/preFormat, but that should be documented.

support redirect options

Usually in the production environment application error should not display the error message, but redirect to the error page

Mongo db duplicate doc error

When there is a: MongoError: E11000 duplicate I get this error. How can I handle this a bit better?

{
    "message": "Not Found",
    "name": "NotFoundError",
    "stack": "NotFoundError: Not Found\n    at Object.throw (/media/phil/Backup/sys/seoblog/api/node_modules/koa/lib/context.js:97:11)\n    at /media/phil/Backup/sys/seoblog/api/node_modules/koa-json-error/lib/middleware.js:52:58\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)",
    "status": 404
}

How to output just status and message

From the readme it is not clear to me how to have an error that contains just status and message. I know from postFormat that I can omit fields from the response. But I don't want them to be created in the first place. I have to use options.format (Function) to achieve that but how?

Extend no throw error handling

Some middlewares I use won't don't throw when something is wrong, but will return a 500.
Currently you handle only 404:

shouldThrow404(ctx.status, ctx.body) && ctx.throw(404);

It would nice to handle all error status (maybe make is configurable by the user).
It's not that complicated, I don't have time!

The ability to customize http code when ctx.thow

Hey, I use json-error recently and found it great. I really appreciate your work.

Is there any plan to add a feature of customize http code when ctx.thow, just like:

app.use(koaJsonError({ status: 200 }))

I just want to set http code 200 and only put the error code into response body of my end point api.

Thanks, anyway.

Consider adding a simple format function

This is meant to simplify the current API and offer an alternative to the preFormat, format, postFormat functions, which may be confusing some users.

In addition to allow passing an options object, we may benefit from receiving a single function instead which should behave as a shorthand for:

let opts = {
   format: (err) => {
      let obj = {};
      // Modify `obj` in any way
      return obj;
   }
}
app.use(error(opts));

So, the above should be equivalent to:

function formatError(err) {
  let obj = {};
  // Modify `obj` in any way
  return obj;
} 
app.use(error(formatError));

Docs should also be updated.

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.