Skip to content

Getting started ​

Install ​

sh
npm i unknown-error
sh
pnpm add unknown-error
sh
yarn add unknown-error

TIP

unknown-error is ESM only, and runs in Node.js 24 or later, Deno, Bun and browsers. From CommonJS, load it with a dynamic import: const { toError } = await import('unknown-error');

Convert a caught value ​

Pass the catch variable to toError. Whatever was thrown, you get an Error:

ts
import { 
toError
} from 'unknown-error';
try {
doWork
();
} catch (
err
) {
const
error
=
toError
(
err
);
const error: Error
console
.
error
(
error
.
message
);
}

An Error comes back unchanged. Anything else becomes a new Error that describes it:

ts
toError
('boom').
message
; // 'boom'
toError
({
status
: 404 }).
message
; // '{"status":404}'
toError
({
message
: 'Not found' }).
message
; // 'Not found'

When you only need the text, getErrorMessage(err) is the same as toError(err).message, and can't throw even when reading message does.

Check an error code ​

hasCode checks for a code such as Node's ENOENT, and narrows the type when it matches:

ts
import { 
readFile
} from 'node:fs/promises';
import {
hasCode
} from 'unknown-error';
export const
readOptional
= async (
path
: string):
Promise
<string | null> => {
try { return await
readFile
(
path
, 'utf8');
} catch (
err
) {
if (
hasCode
(
err
, 'ENOENT')) {
return null; } throw
err
;
} };

formatError prints an error with every cause, indented under the error it caused:

ts
const 
error
= new
Error
('Request failed', {
cause
: new
Error
('connect ECONNREFUSED 127.0.0.1:5432'),
});
console
.
log
(
formatError
(
error
));
// Error: Request failed // at ... // Caused by: Error: connect ECONNREFUSED 127.0.0.1:5432 // at ...

Next steps ​