# error-middleware

> More control to express errors

Latest version **5.2.0** (published 2020-05-21) · ISC license · 0 weekly downloads

## Install

```sh
npm install error-middleware
pnpm add error-middleware
yarn add error-middleware
bun add error-middleware
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 5.2.0 |
| Published | 2020-05-21 |
| First published | 2018-04-21 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >=6.4.0 |
| Dependencies | 3 |
| Unpacked size | 87 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 10 |
| Author | Gabriel Siedler |
| Maintainers | gabrielsiedler |
| Keywords | express, express.js, error, middleware |

## Links

- npm: https://www.npmjs.com/package/error-middleware
- Repository: https://github.com/gabrielsiedler/express-error-handler
- Homepage: https://github.com/gabrielsiedler/express-error-handler#readme
- Issues: https://github.com/gabrielsiedler/express-error-handler/issues
- npm.io page: https://npm.io/package/error-middleware

## Dependencies (3)

- [prettier](https://npm.io/package/prettier.md) ^1.19.1
- [tslint-config-prettier](https://npm.io/package/tslint-config-prettier.md) ^1.18.0
- [tslint-consistent-codestyle](https://npm.io/package/tslint-consistent-codestyle.md) ^1.16.0

## Alternatives

- [@sentry/react-native](https://npm.io/package/@sentry/react-native.md) — 2.6M weekly downloads
- [@ardatan/aggregate-error](https://npm.io/package/@ardatan/aggregate-error.md) — 708.1K weekly downloads
- [custom-error-generator](https://npm.io/package/custom-error-generator.md) — 2.0K weekly downloads
- [@technik-sde/prosemirror-recreate-transform](https://npm.io/package/@technik-sde/prosemirror-recreate-transform.md) — 1.5K weekly downloads
- [@suchipi/error-utils](https://npm.io/package/@suchipi/error-utils.md) — 78 weekly downloads

## Recent versions

- 5.2.0 (latest) — 2020-05-21
- 5.1.0 — 2020-05-21
- 5.0.0 — 2020-05-21
- 4.2.3 — 2020-02-04
- 4.2.2 — 2020-02-04
- 4.2.1 — 2020-01-31
- 4.1.1 — 2019-02-18
- 4.0.1 — 2019-02-18
- 4.0.0 — 2019-02-18
- 3.0.0 — 2018-07-24
- 2.0.0 — 2018-07-24
- 1.1.3 — 2018-06-24
- 1.1.1 — 2018-06-22
- 1.0.1 — 2018-04-21
- 1.0.0 — 2018-04-21

## README

<p align="center">
  <img src="./em.png">
</p>

# Error Middleware for Express

![build status](https://img.shields.io/circleci/project/github/gabrielsiedler/error-middleware.svg 'Build status')
[![Coverage Status](https://coveralls.io/repos/github/gabrielsiedler/error-middleware/badge.svg?branch=master)](https://coveralls.io/github/gabrielsiedler/error-middleware?branch=master)

This package handles errors on the express code and returns it with a fixed pattern, without leaks. It works with syncronous and asyncronous route functions.

## Installation

`npm install error-middleware`<br/>
or<br/>
`yarn add error-middleware`

---

## Error Types

Currently the middleware has exposed the following error types:

- `BadRequestError`
- `ForbiddenError`
- `NotFoundError`
- `UnauthorizedError`
- `Validation Error`

But you can also use

- `CustomError`

## Error response format

The consumer will receive a JSON object with `code`, `type` and `error` as folows:

```
{
  code: <error code>,
  type: <error type>,
  error: <error message>
}
```

## Example of expected responses

<table style="width: 100%">
  <tr>
    <th>Code</th>
    <th>Response</th>
  </tr>
  <tr>
    <td>
      <pre lang="js"><code>throw new BadRequestError('User "id" is malformed.')</code></pre>
    </td>
    <td>
      <pre lang="json"><code>
{
  "code": 400,
  "type": "BadRequest",
  "error": "User 'id' is malformed."
}</code></pre>
    </td>
  </tr>
  <tr>
    <td><pre lang="js"><code>
throw new ValidationError({
  name: 'Name is too short.',
  email: 'Invalid email.'
})</code></pre></td>
    <td><pre lang="json"><code>
{
  "code": 400,
  "type": "Validation",
  "error": {
    "name": "Name is too short.",
    "email": "Invalid email."
  }
}</code></pre></td>
  </tr>
  <tr>
    <td><pre lang="js"><code>
throw new CustomError(
  'Not acceptable headers',
  406,
  'NotAcceptable'
)</code></pre></td>
    <td><pre lang="json"><code>
{
  "code": 406,
  "type": "NotAcceptable",
  "error": "Not acceptable headers"
}</code></pre></td>
  </tr>
  <tr>
    <td><pre lang="js"><code>
throw new Error(`Invalid user ${userId}`)
</code></pre></td>
    <td><pre lang="json"><code>
{
  "code": 500,
  "type": "InternalError",
  "error": "An internal error occurred."
}</code></pre></td>
  </tr>
</table>

## How to use

- src/**index.js**<br />
  _Where you declare all your high level routes. The middleware should be last to be able to catch all errors._

  ```js
  import errorMiddleware from 'error-middleware'
  import routes from './routes'

  router.use(routes)

  router.use(errorMiddleware)
  ```

- src/**routes.js**

  ```js
  import { BadRequestError, ValidationError, NotFoundError } from 'error-middleware/errors'

  router.put('/user/:id', (req, res) => {
    const { id } = req.params
    const { name, email } = req.body

    const idRegex = /^\d{4}$/
    if (!idRegex.test(id)) {
      throw new BadRequestError(`User 'id' is malformed.`)
    }

    if (!validate(name, email)) {
      throw new ValidationError({
        name: 'Name should be at least 4 characters long',
        email: 'Invalid email',
      })
    }

    // your update logic goes here
    // { ... }

    res.sendStatus(200)
  })

  router.get('/error', (req, res) => {
    // an endpoint that simulates a pure error being thrown. It will be translated to InternalError and all its content will not be leaked.
    throw new Error('Internal error that should not be leaked.')
  })

  // If no matches found, return 404
  router.use((req, res) => {
    throw new NotFoundError()
  })
  ```

---

Check [examples](./examples/simple-server) for more

---
_Source: https://npm.io/package/error-middleware · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
