HTTP error class
This is a utility error class for representing a HTTP error (or status).
Install
# NPM
npm i @poppanator/http-error
# Yarn
yarn add @poppanator/http-error
Usage
HttpError
Properties
These are the properties exposed, other than the default ones inherited from
the Error class.
statusCode: The HTTP status code, e.g. 400, 404, 500 etc.
statusText: The HTTP status text, e.g. Not Found, Internal Server Error
etc
fullStatusMessage: The HTTP status and text, e.g. 404 Not Found
import { HttpError } from '@poppanator/http-error'
const err1 = new HttpError(307)
err1.statusCode
err1.statusText
err1.message
err1.fullStatusMessage
const err2 = new HttpError(404, 'Lost Some Where')
err2.statusCode
err2.statusText
err2.message
err2.fullStatusMessage
const err3 = new HttpError(500, { message: `That's not good` })
err3.statusCode
err3.statusText
err3.message
err3.fullStatusMessage
const err3 = new HttpError(500, {
statusText: 'Server Broke',
message: `That's not good`,
})
err3.statusCode
err3.statusText
err3.message
err3.fullStatusMessage
This is the constructor signature:
type HttpErrorConstuctorArgs = {
statusText?: string
message?: string
}
constructor(
statusCode: number,
statusTextOrArgs?: string | HttpErrorConstuctorArgs
)
Utility functions
isHttpError()
Check if something is an instance of HttpError
import { isHttpError } from '@poppanator/http-error'
try {
await doSomethingThatMightThrow()
} catch (err: unknown) {
if (isHttpError(err)) {
logger.warn(`Got HTTP error: ${err.fullStatusMessage}`)
} else {
logger.warn(`Got error: ${err.message}`)
}
}
This is the method signature:
export function isHttpError(obj: unknown): obj is HttpError
resolveHttpStatusCode()
When dealing with HTTP client libraries you might end up with a HTTP error
object of sort, but it might not always be clear how to get hold of the
HTTP status code.
This function tries to resolve the status code by looking at various
properties with common status code names.
By default the function will check for the code, status and statusCode
properties and return the value of any of these if the value is a number.
You can also pass additional properties to check in otherProperties
import { resolveHttpStatusCode } from '@poppanator/http-error'
const withCode = { code: 201 }
resolveHttpStatusCode(withCode)
const withStatus = { status: 201 }
resolveHttpStatusCode(withStatus)
const withStatusCode = { statusCode: 201 }
resolveHttpStatusCode(withStatusCode)
const withNonNumeric = { code: '201' }
resolveHttpStatusCode(withNonNumeric)
const withOutKnownProperty = { prop: 201 }
resolveHttpStatusCode(withOutKnownProperty)
const withOutKnownProperty = { prop: 201 }
resolveHttpStatusCode(withOutKnownProperty, ['prop'])
This is the method signature:
type PlainObject<T = any> = { [key: string]: T }
export type IsStatusCodeLike = number | PlainObject
export function resolveHttpStatusCode<T extends string[]>(
arg: IsStatusCodeLike,
otherProperties?: T
): Maybe<number>