Skip to main content

Errors

Helpers for the error paths try/catch leaves awkward — asserting invariants, creating named errors, and pulling a message out of an unknown catch binding. TypeScript types a catch clause as unknown, so getErrorMessage exists to keep that narrowing out of every call site. When failure is an expected outcome rather than an exception, try's Result tuples are usually the better shape.

Example

import { assert, getErrorMessage } from '@rtorcato/js-common/errors'

function publish(post: Post | undefined) {
assert(post, 'post not found') // `post` is `Post` from here on
return post.slug
}

try {
await publish(post)
} catch (err) {
// A catch binding is `unknown`; this is the narrowing you would write by hand.
console.error(getErrorMessage(err))
}

Import

import { assert, createCustomError, getErrorMessage } from '@rtorcato/js-common/errors'

Exports

NameSummary
assertThrows an error if the condition is false.
createCustomErrorCreates a new Error with a custom name and message.
getErrorMessageGets the error message from an unknown error value.
isErrorNameChecks if an error is an instance of a specific error name.
tryWithFallbackWraps a function and catches errors, returning a fallback value if an error occurs.

See also

  • tryResult tuples instead of thrown exceptions
  • promises — delay, timeout and settle helpers
  • validation — type guards — isString, isNumber, isUrl
  • logging — leveled logging and console capture