Skip to main content

@rtorcato/js-common / errors

errors

Functions​

createCustomError()​

createCustomError(name, message): Error

Defined in: errors/index.ts:16

Creates a new Error with a custom name and message.

Example​

const err = createCustomError('NotFoundError', 'user 42 is missing')
err.name // 'NotFoundError'
err.message // 'user 42 is missing'
err instanceof Error // true

Parameters​

name​

string

The error name.

message​

string

The error message.

Returns​

Error

The custom Error object.


isErrorName()​

isErrorName(error, name): boolean

Defined in: errors/index.ts:37

Checks if an error is an instance of a specific error name.

Example​

const err = createCustomError('NotFoundError', 'missing')
isErrorName(err, 'NotFoundError') // true
isErrorName(err, 'TypeError') // false
isErrorName('oops', 'TypeError') // false

Parameters​

error​

unknown

The error to check.

name​

string

The error name to match.

Returns​

boolean

True if the error matches the name, false otherwise.


getErrorMessage()​

getErrorMessage(error): string

Defined in: errors/index.ts:54

Gets the error message from an unknown error value.

Example​

getErrorMessage(new Error('boom')) // 'boom'
getErrorMessage('boom') // 'boom'
getErrorMessage({ code: 500 }) // '{"code":500}'

Parameters​

error​

unknown

The error value.

Returns​

string

The error message, or a stringified version if not an Error.


assert()​

assert(condition, message): asserts condition

Defined in: errors/index.ts:70

Throws an error if the condition is false.

Parameters​

condition​

unknown

The condition to check.

message​

string

The error message to throw if the condition is false.

Returns​

asserts condition


tryWithFallback()​

tryWithFallback<T>(fn, fallback): Promise<T>

Defined in: errors/index.ts:89

Wraps a function and catches errors, returning a fallback value if an error occurs. Use this only when the fallback is genuinely safe and the error can be ignored. For typed error handling, prefer tryCatch from @rtorcato/js-common/try.

Example​

await tryWithFallback(async () => fetchData(), []) // the data, or [] if it throws
await tryWithFallback(() => JSON.parse('{'), {}) // {}

Type Parameters​

T​

T

Parameters​

fn​

() => T | Promise<T>

The function to wrap.

fallback​

T

The fallback value to return on error.

Returns​

Promise<T>