Typed HTTP error classes with status codes, factory methods, and serialization
npm install @philiprehberger/http-errorTyped HTTP error classes with status codes, factory methods, and serialization.
npm install @philiprehberger/http-error
import { HttpError, isHttpError } from '@philiprehberger/http-error';
// Factory methods
throw HttpError.notFound('User not found');
throw HttpError.badRequest('Invalid email');
throw HttpError.internal();
// Constructor
throw new HttpError(409, 'Already exists', { code: 'DUPLICATE' });
// Type guard
try {
await fetchUser(id);
} catch (err) {
if (isHttpError(err, 404)) {
// handle not found
}
}
// Serialization
const err = HttpError.badRequest('Invalid input');
console.log(JSON.stringify(err));
// {"status":400,"message":"Invalid input","code":"ERR_HTTP_400"}
new HttpError(status, message?, options?)Creates an HTTP error instance.
| Param | Type | Description |
|---|---|---|
status | number | HTTP status code |
message | string | Error message (defaults by status) |
options.code | string | Machine-readable code |
options.cause | unknown | Underlying cause |
badRequest, unauthorized, forbidden, notFound, conflict, gone, unprocessable, tooMany, internal, notImplemented, badGateway, unavailable
isHttpError(err): err is HttpErrorisHttpError(err, status): err is HttpErrorType guard that checks if a value is an HttpError, optionally matching a specific status code.
toJSON(): { status, message, code }Serializes the error for API responses.
npm install
npm run build
npm test
If you find this project useful: