# @guilhermemj/app-error

> Error subclass on steroids for custom application exceptions

Latest version **1.1.0** (published 2021-03-16) · Apache-2.0 license · 0 weekly downloads

## Install

```sh
npm install @guilhermemj/app-error
pnpm add @guilhermemj/app-error
yarn add @guilhermemj/app-error
bun add @guilhermemj/app-error
```

## Health

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

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.0 |
| Published | 2021-03-16 |
| First published | 2021-03-08 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 18.5 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Guilherme Jacomini |
| Maintainers | guilhermemj |
| Keywords | error, exception, custom-error |

## Links

- npm: https://www.npmjs.com/package/@guilhermemj/app-error
- Repository: https://github.com/guilhermemj/app-error
- Homepage: https://github.com/guilhermemj/app-error#readme
- Issues: https://github.com/guilhermemj/app-error/issues
- npm.io page: https://npm.io/package/@guilhermemj/app-error

## Dependencies (1)

- [uuid](https://npm.io/package/uuid.md) ^8.3.2

## 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

- 1.1.0 (latest) — 2021-03-16
- 1.0.0 — 2021-03-08

## README

# App Error

Make application errors easier to handle

- [Installation](#installation)
- [Usage](#usage)
  - [Presets](#presets)
- [Options](#options)
  - [`httpStatusCode`](#httpstatuscode)
  - [`code`](#code)
  - [`level`](#level)
  - [`meta`](#meta)

## Installation

``` bash
npm install @guilhermemj/app-error
```

## Usage

Simply throw an `AppError` like you would with any normal `Error`. You can, however, pass a second argument with some options to customize error context and meta info.

``` javascript
var AppError = require("@guilhermemj/app-error");

// Basic usage
throw new AppError("Ops, something went wrong!");

throw new AppError("Resource not found!", {
  httpStatusCode: 404,
  code: "ERR_NOT_FOUND",
});

// Full customization
throw new AppError("Resource version differs from database", {
  httpStatusCode: 409,
  code: "ERR_RESOURCE_CONFLICT",
  level: "warn",
  meta: {
    user: "@johndoe",
    resourceId: "123456",
    informedData: {/* ... */},
    expectedData: {/* ... */},
  },
});
```

Where `AppError` really shines is when catching and handling thrown errors. Besides the mentioned options, each error has an unique `id` and `date` object making it very easy to log errors and normalize API responses.

Here, we simulate an express controller response with a totally arbitrary logger function to show the difference between handling an `AppError` and other common errors:

``` javascript
var AppError = require("@guilhermemj/app-error");

try {
  // Do some code...
} catch (error) {
  if (error instanceof AppError) {
    logger[error.level](error.message, error.code, {
      // `meta` may have important info about error context
      meta: error.meta,
      date: error.date,
      uuid: error.id,
    });

    res.status(error.httpStatusCode).json({
      message: error.message,
      code: error.code,
      uuid: error.id,
    });
  } else {
    // Something REALLY bad happened! But we only have a message to log :(
    logger.error(error.message, "ERR_INTERNAL_ERROR", { date: new Date() });

    res.status(500).json({
      message: error.message,
      code: "ERR_INTERNAL_ERROR",
    });
  }
}
```

Please note how we are able to log much richier information with `AppError` and how easy it is to identify it's instances.

### Presets

In order to improve code DRYness it's recommended to create some presets for common errors in your application. Typescript users have the `AppErrorOptions` interface available for this purpose.

To avoid destructuring and other workarounds when using presets, `AppError` constructor accepts a third parameter to be used as the `meta` object option.

``` typescript
import AppError, { AppErrorOptions } from "@guilhermemj/app-error";

const ERR_INVALID_CONFIG: AppErrorOptions = {
  httpStatusCode: 400,
  code: "ERR_INVALID_CONFIG",
  level: "debug",
};

if (!isValidEmail(payload.email)) {
  throw new AppError(`"${payload.email}" is not a valid email`, ERR_INVALID_CONFIG, { payload, invalidField: "email" });
}

if (!payload.password) {
  throw new AppError("Password is required", ERR_INVALID_CONFIG, { payload, invalidField: "password" });
}
```

## Options

### `httpStatusCode`

- **Type:** `number`
- **Default:** `500`

Status code to be used on API responses. ([List of existing codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status))

### `code`

- **Type:** `string`
- **Default:** `"ERR_UNCAUGHT_EXCEPTION"`

Error code. Can be used to identify errors of the same type.

### `level`

- **Type:** `"error" | "warn" | "info" | "debug"`
- **Default:** `"error"`

Error severity level. Useful for logging.

### `meta`

- **Type:** `Object`
- **Default:** `{}`

Extra info about the error to be retrieved later.

It's very common to enrich logs and API responses with some execution context. This is where you should store it.

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