JSPM

@rtorcato/api-errors

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 775
  • Score
    100M100P100Q80695F
  • License MIT

Framework-agnostic HTTP error classes for Node.js APIs.

Package Exports

  • @rtorcato/api-errors

Readme

@rtorcato/api-errors

Framework-agnostic HTTP error classes for Node.js APIs.

Install

pnpm add @rtorcato/api-errors

Usage

import {
  BadRequestError,
  ConflictError,
  ForbiddenError,
  HttpError,
  InternalServerError,
  NotFoundError,
  UnauthorizedError,
} from '@rtorcato/api-errors'

throw new NotFoundError('User not found', 'user_not_found')
// err.status  -> 404
// err.code    -> 'user_not_found'
// err.message -> 'User not found'

Every class extends HttpError, which extends Error. Each carries:

  • status — HTTP status code (number)
  • code — machine-readable error code (string)
  • message — human-readable message (inherited from Error)

Available classes

Class Status Default code
BadRequestError 400 bad_request
UnauthorizedError 401 unauthorized
ForbiddenError 403 forbidden
NotFoundError 404 not_found
ConflictError 409 conflict
InternalServerError 500 internal_server_error

HttpError itself is also exported for custom statuses:

throw new HttpError(429, 'Too many requests', 'rate_limited')

Source + changelog: https://github.com/rtorcato/api-common/tree/main/packages/api-errors