1.0.1 • Published 8 years ago

@starefossen/http-error v1.0.1

Weekly downloads
12
License
MIT
Repository
github
Last release
8 years ago

HttpError

Build status Codacy grade Codacy coverage NPM downloads NPM version Node version Dependency status

HTTP aware Error class HttpError for all your Node.js applications.

Purpose

The HttpError serves two purposes. First to attach a status code to error objects in one single operation, and second to encapsulate lower lever errors in application specific errors that can be presented to users without decoupling or loss of important technical details.

Install

$ npm install --save @starefossen/http-error

Usage

const HttpError = require('@starefossen/http-error');
const express = require('express');

const app = express();

app.get('/some/route', (req, res, next) => {
  db.get({…}, (err, data) => {
    if (err) { return next(new HttpError('Database Query Failed', 500, err)); }
    if (!data) { return next(new HttpError('Object Not Found', 404)); }

    // do work here
  });
});

app.use((req, res, next, httpError) => {
  // print system errors to stderr
  if (httpError.code > 500) {
    if (httpError.error) {
      console.error(httpError.error.message);
      console.error(httpError.error.stack);
    } else {
      console.error(httpError.message);
      console.error(httpError.stack);
    }
  }

  res.status(httpError.code);
  res.end();
});

MIT Licensed