@giancosta86/format-error
v2.1.0
Published
Lightweight library for modern Error formatting
Downloads
85
Maintainers
Readme
format-error
Lightweight library for modern Error formatting
format-error is a TypeScript library designed to easily convert Error
objects to string
; in particular, its formatError()
function provides:
support for the
cause
property introduced by ES 2022customizable behaviour via an optional
parts
parameterbackward compatibility with non-Error objects
Installation
npm install @giancosta86/format-error
or
yarn add @giancosta86/format-error
The public API entirely resides in the root package index, so you shouldn't reference specific modules.
Usage
The library provides the following utility functions:
formatError(error[,parts])
: given an error value, returns a string including just the requested error parts (see below). By default, only the class and the message are included.The
error
argument can be anything - although non-Error
objects will be converted without considering theparts
argument. More precisely:If the object includes a
message
property, its string conversion will be returnedOtherwise, the value itself is converted to string
toError(error)
: when receiving anError
, the function just returns the argument itself; otherwise, it creates an error whose message is the stringified value
Error parts
ErrorParts
is a flag enum - describing the different parts of an Error
that should appear in the result:
Class
: the classMessage
: the message
CauseChain
: the chain ofcause
errors - if available - displaying the related class and message parts according to the current formatStack
: the stack trace
You can request multiple error parts by combining the enum values - for example:
formatError(
new URIError("Yogi the Bear"),
ErrorParts.Class | ErrorParts.CauseChain
);
Additionally, the shortcut combination values Core
, Main
and All
are available.
Please, note: you must specify at least one between Class
and Message
; otherwise, the function will throw an error