Skip to content
This repository has been archived by the owner on Nov 15, 2022. It is now read-only.

Starefossen/node-http-error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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