• Stars
    star
    169
  • Rank 223,661 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A graceful error handler for Express and Restify applications.

express-error-handler

A graceful error handler for Express applications. This also patches a DOS exploit where users can manually trigger bad request errors that shut down your app.

Quick start:

var express = require('express'),
  errorHandler = require('../error-handler.js'),
  app = express(),
  env = process.env,
  port = env.myapp_port || 3000,
  http = require('http'),
  server;

// Route that triggers a sample error:
app.get('/error', function createError(req,
    res, next) {
  var err = new Error('Sample error');
  err.status = 500;
  next(err);
});

// Create the server object that we can pass
// in to the error handler:
server = http.createServer(app);

// Log the error
app.use(function (err, req, res, next) {
  console.log(err);
  next(err);
});

// Respond to errors and conditionally shut
// down the server. Pass in the server object
// so the error handler can shut it down
// gracefully:
app.use( errorHandler({server: server}) );

server.listen(port, function () {
  console.log('Listening on port ' + port);
});

Configuration errorHandler(options)

Here are the parameters you can pass into the errorHandler() middleware:

  • @param {object} [options]

  • @param {object} [options.handlers] Custom handlers for specific status codes.

  • @param {object} [options.views] View files to render in response to specific status codes. Specify a default with options.views.default

  • @param {object} [options.static] Static files to send in response to specific status codes. Specify a default with options.static.default.

  • @param {number} [options.timeout] Delay between the graceful shutdown attempt and the forced shutdown timeout.

  • @param {number} [options.exitStatus] Custom process exit status code.

  • @param {object} [options.server] The app server object for graceful shutdowns.

  • @param {function} [options.shutdown] An alternative shutdown function if the graceful shutdown fails.

  • @param {function} serializer a function to customize the JSON error object. Usage: serializer(err) return errObj

  • @param {function} framework Either 'express' (default) or 'restify'.

  • @return {function} errorHandler Express error handling middleware.

Examples:

express-error-handler lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:

var errorHandler = require('express-error-handler'),
  handler = errorHandler({
    handlers: {
      '404': function err404() {
        // do some custom thing here...
      }
    }
  });

// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );

// Handle all unhandled errors:
app.use( handler );

Or for a static page:

handler = errorHandler({
  static: {
    '404': function err404() {
      // do some custom thing here...
    }
  }
});

Or for a custom view:

handler = errorHandler({
  views: {
    '404': function err404() {
      // do some custom thing here...
    }
  }
});

Or for a custom JSON object:

var errorHandler = require('express-error-handler'),
  handler = errorHandler({
    serializer: function(err) {
      var body = {
        status: err.status,
        message: err.message
      };
      if (createHandler.isClientError(err.status)) {
        ['code', 'name', 'type', 'details'].forEach(function(prop) {
          if (err[prop]) body[prop] = err[prop];
        });
      }
      return body;
    }
  });

More examples are available in the examples folder.

errorHandler.isClientError(status)

Return true if the error status represents a client error that should not trigger a restart.

  • @param {number} status
  • @return {boolean}

Example

errorHandler.isClientError(404); // returns true
errorHandler.isClientError(500); // returns false

errorHandler.httpError(status, [message])

Take an error status and return a route that sends an error with the appropriate status and message to an error handler via next(err).

  • @param {number} status
  • @param {string} message
  • @return {function} Express route handler
// Define supported routes
app.get( '/foo', handleFoo() );
// 405 for unsupported methods.
app.all( '/foo', createHandler.httpError(405) );

Restify support

Restify error handling works different from Express. To trigger restify mode, you'll need to pass the framework parameter when you create the errorHandler:

var handleError = errorHandler({
  server: server
  framework: 'restify'
});

In restify, next(err) is synonymous with res.send(status, error). This means that you should only use next(err) to report errors to users, and not as a way to aggregate errors to a common error handler. Instead, you can invoke an error handler directly to aggregate your error handling in one place.

There is no error handling middleware. Instead, use server.on('uncaughtException', handleError)

See the examples in ./examples/restify.js

Credit and Thanks

Written by Eric Elliott for the book, "Programming JavaScript Applications" (O'Reilly)

More Repositories

1

rtype

Intuitive structural type notation for JavaScript.
JavaScript
1,129
star
2

react-pure-component-starter

A pure component dev starter kit for React.
JavaScript
792
star
3

autodux

Automate the Redux boilerplate.
JavaScript
592
star
4

h5Validate

An HTML5 form validation plugin for jQuery. Works on all major browsers, both new and old. Implements inline, realtime validation best practices (based on surveys and usability studies). Developed for production use in e-commerce. Currently in production with millions of users.
JavaScript
577
star
5

moneysafe

Convenient, safe money calculations in JS
JavaScript
452
star
6

credential

Easy password hashing and verification in Node. Protects against brute force, rainbow tables, and timing attacks.
JavaScript
348
star
7

rfx

Self documenting runtime interfaces.
JavaScript
277
star
8

redux-dsm

Declarative state machines for Redux: Reduce your async-state boilerplate.
JavaScript
222
star
9

speculation

JavaScript promises are made to be broken. Speculations are cancellable promises.
JavaScript
197
star
10

irecord

An immutable store that exposes an RxJS observable. Great for React.
JavaScript
192
star
11

the-software-developers-library

The Software Developer's Library: a treasure trove of books for people who love code. Curated by Eric Elliott
192
star
12

react-things

A exploratory list of React ecosystem solutions
174
star
13

feature-toggle

A painless feature toggle system in JavaScript. Decouple development and deployment.
JavaScript
155
star
14

ogen

Write synchronous looking code & mix synchronous & asynchronous results using generators & observables.
JavaScript
129
star
15

tdd-es6-react

Examples of TDD in ES6 with React
95
star
16

react-hello

A hello world example React app
JavaScript
63
star
17

fluentjs1

Talk - Fluent JavaScript Part 1: Prototypal OO. Learn to code like a JS native. Take advantage of JavaScript's distinguishing features in order to write better code.
JavaScript
53
star
18

neurolib

Neuron emulation tools
JavaScript
52
star
19

the-two-pillars-of-javascript-talk

References from "The Two Pillars of JavaScript" talk
51
star
20

maybearray

Native JavaScript Maybes built with arrays.
JavaScript
49
star
21

qconf

Painless configuration with defaults file, environment variables, arguments, function parameters.
JavaScript
45
star
22

object-list

Treat arrays of objects like a db you can query.
JavaScript
43
star
23

gql-validate

Validate a JS object against a GraphQL schema
JavaScript
33
star
24

bunyan-request-logger

Automated request logging middleware for Express. Powered by Bunyan.
JavaScript
29
star
25

tinyapp

A minimal, modular, client-side application framework.
JavaScript
28
star
26

arraygen

Turn any array into a generator.
JavaScript
28
star
27

dpath

Dot Path - FP sugar for immutables
JavaScript
22
star
28

rootrequire

npm install --save rootrequire # then `var root = require('rootrequire'), myLib = require(root + '/path/to/lib.js');`
JavaScript
19
star
29

siren-resource

Resourceful routing with siren+json hypermedia for Express.
JavaScript
18
star
30

version-healthcheck

A plug-and-play /version route for the Node.js Express framework.
JavaScript
17
star
31

react-easy-universal

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.
JavaScript
16
star
32

odotjs

A prototypal OO library for JavaScript
JavaScript
13
star
33

todotasks

TodoMVC for task runners. Not sure which task runner to use? Take a look at some reference implementations.
JavaScript
12
star
34

react-test-demo

React Test Demo
CSS
12
star
35

react-faves

Favorite React Tools
12
star
36

jiron

Make your API self documenting and your clients adaptable to API changes.
11
star
37

JSbooks

Directory of free Javascript ebooks
CSS
11
star
38

saas-questions

SaaS Questions: The most important questions every SaaS company should have answers to.
10
star
39

applitude

JavaScript application namespacing and module management.
JavaScript
8
star
40

grange

Generate all sorts of values based on a range of numbers.
JavaScript
7
star
41

talks-and-interviews

A list of my talks and interviews.
7
star
42

tinyerror

Easy custom errors in browsers, Node, and Applitude
JavaScript
7
star
43

jQuery.outerHTML

A tiny outerHTML shim for jQuery
JavaScript
6
star
44

connect-cache-control

Connect middleware to prevent the browser from caching the response.
JavaScript
6
star
45

nfdata

NFData - A metadata proposal for NFT interoperability
5
star
46

xforms

xforms
JavaScript
5
star
47

sparkly

Ignite Learning, Inspire Creation
CSS
5
star
48

clctr

Event emitting collections with iterators (like Backbone.Collection).
JavaScript
3
star
49

ofilter

Array.prototype.filter for objects.
JavaScript
3
star
50

rejection

You gotta lose to win.
JavaScript
3
star
51

colab

A project collaboration platform centered on live video streaming and monetization.
CSS
3
star
52

slides-intro-to-js-objects

A basic (and short) overview of objects in JavaScript.
JavaScript
2
star
53

slides-modular-javascript

Modular JavaScript With npm and Node Modules
CoffeeScript
2
star
54

testling-jasmine

run jasmine tests in all the browsers with testling
JavaScript
2
star
55

hifi

Flow based programming for Node services.
1
star
56

resource-acl

An ACL intended for use with express-resource.
1
star
57

pja-guestlist-client

The browser client for Guestlist. A demo app for Programming JavaScript Applications.
JavaScript
1
star
58

course-primer

A primer for the "Learn JavaScript with Eric Elliott" course series. Prerequisite for all courses.
1
star
59

mapall

Given an array of promises, map to a same-ordered array of resolutions or rejections.
1
star
60

pja-sections

Draft sections for "Programming JavaScript Applications"
1
star
61

maybe-assign

Like Object.assign, but skip null or undefined props.
1
star