Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fastify/fastify-error
https://github.com/fastify/fastify-error
fastify fastify-library
Last synced: 2 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/fastify/fastify-error
- Owner: fastify
- License: mit
- Created: 2020-06-21T13:38:33.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-09-11T17:45:19.000Z (3 months ago)
- Last Synced: 2024-10-29T14:46:41.347Z (about 2 months ago)
- Topics: fastify, fastify-library
- Language: JavaScript
- Homepage:
- Size: 104 KB
- Stars: 106
- Watchers: 17
- Forks: 20
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @fastify/error
[![CI](https://github.com/fastify/fastify-error/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/fastify/fastify-error/actions/workflows/ci.yml)
[![NPM version](https://img.shields.io/npm/v/@fastify/error.svg?style=flat)](https://www.npmjs.com/package/@fastify/error)
[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.
### Install
```
npm i @fastify/error
```### Usage
The module exports a function that you can use for consistent error objects, it takes 4 parameters:
```
createError(code, message [, statusCode [, Base]])
```- `code` (`string`, required) - The error code, you can access it later with `error.code`. For consistency, we recommend prefixing plugin error codes with `FST_`
- `message` (`string`, required) - The error message. You can also use interpolated strings for formatting the message.
- `statusCode` (`number`, optional) - The status code that Fastify will use if the error is sent via HTTP.
- `Base` (`ErrorConstructor`, optional) - The base error object that will be used. (eg `TypeError`, `RangeError`)```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello')
console.log(new CustomError()) // error.message => 'Hello'
```How to use an interpolated string:
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s')
console.log(new CustomError('world')) // error.message => 'Hello world'
```How to add cause:
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s')
console.log(new CustomError('world', {cause: new Error('cause')}))
// error.message => 'Hello world'
// error.cause => Error('cause')
```### TypeScript
It is possible to limit your error constructor with a generic type using TypeScript:
```ts
const CustomError = createError<[string]>('ERROR_CODE', 'Hello %s')
new CustomError('world')
//@ts-expect-error
new CustomError(1)
```## License
Licensed under [MIT](./LICENSE).