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

Commit

Permalink
Initial
Browse files Browse the repository at this point in the history
  • Loading branch information
onbjerg committed Jan 22, 2017
0 parents commit 2e2d4ab
Show file tree
Hide file tree
Showing 7 changed files with 1,162 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# build output
dist

# dependencies
node_modules
Empty file added .npmignore
Empty file.
135 changes: 135 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# `micro-boom` [![NPM](https://img.shields.io/npm/v/micro-boom.svg?style=flat)](https://www.npmjs.org/package/micro-boom) [![travis-ci](https://travis-ci.org/onbjerg/micro-boom.svg?branch=master)](https://travis-ci.org/onbjerg/micro-boom)

Wraps errors in [`micro`](https://github.com/zeit/micro) services [`Boom`](https://github.com/hapijs/boom) errors.

**Example Responses**

```json
{
"error": "Unauthorized",
"message": "Not authenticated",
"statusCode": 401
}
```

```json
{
"data": {
"reason": "Username is wrong"
},
"error": "Unauthorized",
"message": "Not authenticated",
"statusCode": 401
}
```

---

## Installation

```sh
npm install --save micro-boom
```

Or even better

```sh
yarn add micro-boom
```

## Import and Usage Example

```js
const { handleErrors, createError } = require('micro-boom')

module.exports = handleErrors(async function (req, res) {
throw createError(401, 'Not authenticated', {
reason: 'Bad password'
})
})
```

## API

#### handleErrors

Catches error from an async function, wraps them in a Boom error object and generates a JSON response.

The status code of an error is determined by three factors, in order:

- Status code is set to `err.output.statusCode`
- If not set, error is inferred from `res.statusCode`
- Default to HTTP 500 (also defaults to HTTP 500 if status is < 400)

**Parameters**

- `fn` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** Async function, your normal `micro` logic.
- `dump` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Optional. Dumps `err.stack` to `stderr` if true

**Examples**

```js
const { handleErrors } = require('micro-boom')

// Returns HTTP 500
module.exports = handleErrors(async function (req, res) {
throw Error('Uh-oh, something bad happened.')
})
```

```js
const { handleErrors } = require('micro-boom')

// Returns HTTP 401
module.exports = handleErrors(async function (req, res) {
res.statusCode = 401
throw Error('Unauthorized')
})
```

Returns an async **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)**.

#### createError

Alias for [`Boom#create(statusCode, [message], [data])`](https://github.com/hapijs/boom#createstatuscode-message-data).

**Parameters**

- `statusCode` **[Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** HTTP status code, must be >= 400
- `message` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** An optional error message.
- `message` **[Any]** Some optional error metadata, serialized with [``JSON.stringify``](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).

**Examples**

```js
const { handleErrors, createError } = require('micro-boom')

// Message defaults to what corresponds to the HTTP error code
module.exports = handleErrors(async function (req, res) {
throw createError(500)
})
```

```js
const { handleErrors, createError } = require('micro-boom')

// HTTP 401: Unauthorized
module.exports = handleErrors(async function (req, res) {
throw createError(401, 'Unauthorized')
})
```

```js
const { handleErrors, createError } = require('micro-boom')

// HTTP 401: Unauthorized with metadata,
// set in `.data` of the response.
module.exports = handleErrors(async function (req, res) {
throw createError(401, 'Unauthorized', {
reason: 'Bad password',
foo: 'bar'
})
})
```

Returns an async **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)**.
53 changes: 53 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const { send } = require('micro')
const Boom = require('boom')

/**
* Catches error from an async function, wraps them
* in a Boom error object and generates a JSON response.
*
* @param {Function} fn Async function, your normal `micro` logic
* @param {Boolean} dump Dumps `err.stack` to `stderr` if true
* @return {void}
*/
module.exports.handleErrors = function (fn, dump = false) {
return async function (req, res) {
try {
return await fn(req, res)
} catch (err) {
// Dump stacktrace if flagged
if (dump) {
console.error(err.stack)
}

// Determine status code in determined order
let status = res.statusCode || 500
if (err.isBoom) {
status = err.output.statusCode
}

// Since it's an error, it's safe to assume <400
// status codes are a mistake.
if (status < 400) {
status = 500
}

// Wrap the error and generate the response
const error = Boom.wrap(err, status)
send(
res,
status,
Object.assign({},
error.output.payload,
error.data && { data: error.data }
)
)
}
}
}

/**
* Creates a Boom error.
*
* @type {@link module:Boom.create}
*/
module.exports.createError = Boom.create
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "micro-boom",
"version": "1.0.0",
"description": "Wraps errors in micro with Boom",
"main": "dist/index.js",
"repository": "https://github.com/onbjerg/micro-boom",
"author": "Oliver Nordbjerg <hi@notbjerg.me>",
"license": "MIT",
"dependencies": {
"async-to-gen": "^1.3.0",
"boom": "^4.2.0"
},
"peerDependencies": {
"micro": "*"
},
"devDependencies": {
"standard": "^8.6.0"
},
"scripts": {
"prepublish": "npm run build",
"build": "mkdir -p dist && async-to-gen index.js > dist/index.js",
"lint": "standard"
}
}
6 changes: 6 additions & 0 deletions travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"sudo": false,
"language": "node_js",
"node_js": 6,
"script": "npm run lint"
}
Loading

0 comments on commit 2e2d4ab

Please sign in to comment.