Skip to content

create error object with http status code for express

Notifications You must be signed in to change notification settings

benpptung/http-error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

http-error

HTTP Error utilities based on @lvigil/err.

Install

pnpm add @lvigil/http-error

Usage

import { NotFound, BadRequest, HttpErr, OnErNotFound } from '@lvigil/http-error'

// 404
if (!user) throw NotFound({ userId })

// 400 with context
if (!valid) throw BadRequest({ input })

// Generic HTTP error
throw HttpErr(403, { userId, path, grant, gate })

// Wrap existing error
catch (err) {
  throw OnErNotFound(err, { userId })
}

API

  • HttpErr(status, [context_dict], [flag_dict]) - Generic HTTP error (400-599)

Shorthand for common HTTP errors:

  • NotFound(), BadRequest(), Unauthorized(), Forbidden(), InternalServerErr(), etc.

  • OnErNotFound(err), OnErBadRequest(err), etc. - Wrap existing errors

All errors have .status property.

err.message is always HTTP status text (e.g. "Not Found"). Use .m() to append messages for debugging.

throw NotFound({ userId }).m('user lookup failed')
// err.message === 'Not Found'
// err.msgs === ['Not Found', 'user lookup failed']

OnEr<Name> error instance also set err.message to HTTP status text, but preserve the original message in history:

const e = new Error('db connection failed')
throw OnErInternalServerErr(e)
// err.message === 'Internal Server Error'
// err.msgs === ['db connection failed', 'Internal Server Error']

See @lvigil/err for the full error API.

About

create error object with http status code for express

Resources

Stars

Watchers

Forks

Packages

No packages published