Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-pig-walrus committed Feb 15, 2016
0 parents commit 9cfeacc
Show file tree
Hide file tree
Showing 8 changed files with 282 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"extends": [
"eslint-config-airbnb/rules/best-practices",
"eslint-config-airbnb/rules/errors",
"eslint-config-airbnb/rules/es6",
"eslint-config-airbnb/rules/legacy",
"eslint-config-airbnb/rules/node",
"eslint-config-airbnb/rules/style",
"eslint-config-airbnb/rules/variables"
],
"env": {
"browser": false,
"node": true,
"es6": true
},
"rules": {
"semi": [2, "never"],
"no-unexpected-multiline": 2,
"indent": [2, 4, {"SwitchCase": 0, "VariableDeclarator": 1}],
"max-len": [2, 120],
"strict": [2, "global"],
"func-names": [0]
},
"plugins": [
],
"ecmaFeatures": {
"modules": false,
"generators": true,
"blockBindings": true,
"classes": true,
"templateStrings": true,
"forOf": true
}
}
49 changes: 49 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# mac
.DS_Store
.localized

# jetbrains
/.idea/

# covergae output
/coverage/

# env vars
/export_env.source

/build/
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_js:
- "5.2"
language: node_js
script: "npm run-script test-travis"
after_script: "npm install coveralls && cat ./coverage/lcov.info | coveralls"
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Scott Lessans

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Exprest (express + REST) Error Handler

[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Dependencies][deps-image]][deps-url]
[![Dev Dependencies][deps-dev-image]][deps-dev-url]

A simple, configurable, REST error handler for express

[npm-image]: https://img.shields.io/npm/v/exprest-error-handler.svg?style=flat-square
[npm-url]: https://npmjs.org/package/exprest-error-handler

[travis-image]: https://img.shields.io/travis/slessans/exprest-error-handler.svg?style=flat-square
[travis-url]: https://travis-ci.org/slessans/exprest-error-handler

[coveralls-image]: https://img.shields.io/coveralls/slessans/exprest-error-handler.svg?style=flat-square
[coveralls-url]: https://coveralls.io/github/slessans/exprest-error-handler

[deps-image]: https://img.shields.io/david/slessans/exprest-error-handler.svg?style=flat-square
[deps-url]: https://david-dm.org/slessans/exprest-error-handler

[deps-dev-image]: https://img.shields.io/david/dev/slessans/exprest-error-handler.svg?style=flat-square
[deps-dev-url]: https://david-dm.org/slessans/exprest-error-handler#info=devDependencies
69 changes: 69 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'use strict'

const DEFAULTS = {
showStackTrace: false,
showNonPublic: false,
includeRawError: false,
}

/**
* Extracts json content of error into json serializable object.
*
* @param {Error} error to extract
* @param {boolean} includeStackTrace true if include stack trace
* @returns {object} content
*/
const extractJsonContent = (error, includeStackTrace) => {
const json = {
error: `${error.message}`,
}
if (error.jsonDetail) {
json.detail = error.jsonDetail
}
if (includeStackTrace && error.stack) {
const lines = error.stack.split('\n')
const reason = lines.shift()
json._stackTrace = {
reason,
at: lines.map((line) => line.trim()),
}
}
return json
}

/**
* Handles errors by outputting to json. If err.status is truthy, this is considered a "public" error.
*
* @param {object} [options] options for error handling
* @param {boolean} [options.showStackTrace] show stack trace in error output, default: false
* @param {boolean} [options.showNonPublic] show underlying error embedded in non-public errors, default: false
* @param {boolean} [options.includeRawError] include actual error object with no changes, default: false
* @returns {Function} error handler suitable for placement on root application.
*/
module.exports = (options) => {
const o = Object.assign({}, DEFAULTS, options || {})

return (err, req, res, next) => { // eslint-disable-line no-unused-vars
let json
let status
if (err.status) {
// this is an error that is ok to show to the public
status = err.status
json = extractJsonContent(err, o.showStackTrace)
} else {
status = 500
json = { error: 'An internal server error occurred.' }
if (o.showNonPublic) {
json._underlyingError = extractJsonContent(err, o.showStackTrace)
}
}

if (o.includeRawError) {
json._rawUnderlyingError = err
}

res
.status(status)
.json(json)
}
}
43 changes: 43 additions & 0 deletions index_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict'
/* eslint-env mocha */

const makeErrorHandler = require('./index')
const express = require('express')
const request = require('supertest')


const _makeTest = (error, handlerOptions, runTest) => (done) => {
const errorHandler = makeErrorHandler(handlerOptions)
const app = express()

app.use('/', (req, res, next) => {
next(error)
})

app.use(errorHandler)

const r = request(app).get('/')
runTest(r)
r.end(done)
}

const _test = (error, handlerOptions, status, json) => _makeTest(error, handlerOptions, (r) => {
if (status !== null) {
r.expect(status)
}
if (json !== null) {
r.expect(json)
}
})

describe('exprest-error-handler', () => {
describe('non public errors', () => {
const error = new Error('unknown error')
it('should use status of 500', _test(
error, null, 500, null
))
it('should use default json response', _test(
error, null, null, { error: 'An internal server error occurred.' }
))
})
})
37 changes: 37 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "exprest-error-handler",
"version": "1.0.0",
"description": "A simple, configurable REST error handler for express",
"main": "index.js",
"scripts": {
"lint": "./node_modules/.bin/eslint index.js index_spec.js",
"pretest": "npm run-script lint",
"test": "./node_modules/.bin/istanbul cover -x **/*_spec.js ./node_modules/.bin/_mocha index_spec.js -- --recursive",
"pretest-travis": "npm run-script lint",
"test-travis": "node_modules/.bin/istanbul cover -x **/*_spec.js ./node_modules/.bin/_mocha index_spec.js --report lcovonly -- --reporter dot"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/slessans/exprest-error-handler.git"
},
"keywords": [
"express",
"rest",
"error",
"handler"
],
"author": "Scott Lessans",
"license": "MIT",
"bugs": {
"url": "https://github.com/slessans/exprest-error-handler/issues"
},
"homepage": "https://github.com/slessans/exprest-error-handler#readme",
"devDependencies": {
"eslint": "1.10.3",
"eslint-config-airbnb": "5.0.1",
"express": "4.13.4",
"istanbul": "0.4.2",
"mocha": "2.4.5",
"supertest": "1.2.0"
}
}

0 comments on commit 9cfeacc

Please sign in to comment.