@ptkhanh94npm/earum-libero-nobis
v1.0.0
Published
![CI](https://github.com/ptkhanh94npm/earum-libero-nobis/workflows/CI/badge.svg) [![NPM version](https://img.shields.io/npm/v/@ptkhanh94npm/earum-libero-nobis.svg?style=flat)](https://www.npmjs.com/package/@ptkhanh94npm/earum-libero-nobis) [![js-standard-
Downloads
3
Maintainers
Keywords
Readme
@ptkhanh94npm/earum-libero-nobis
A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.
Install
npm i @ptkhanh94npm/earum-libero-nobis
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 witherror.code
. For consistency, we recommend prefixing plugin error codes withFST_
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. (egTypeError
,RangeError
)
const createError = require('@ptkhanh94npm/earum-libero-nobis')
const CustomError = createError('ERROR_CODE', 'Hello')
console.log(new CustomError()) // error.message => 'Hello'
How to use an interpolated string:
const createError = require('@ptkhanh94npm/earum-libero-nobis')
const CustomError = createError('ERROR_CODE', 'Hello %s')
console.log(new CustomError('world')) // error.message => 'Hello world'
How to add cause:
const createError = require('@ptkhanh94npm/earum-libero-nobis')
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:
const CustomError = createError<[string]>('ERROR_CODE', 'Hello %s')
new CustomError('world')
//@ts-expect-error
new CustomError(1)
License
Licensed under MIT.