Package Exports
- @whi/http-errors
- @whi/http-errors/lib/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@whi/http-errors) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@whi/http-errors
TypeScript HTTP error classes with Web Response API conversion utilities for modern JavaScript runtimes.
Installation
npm install @whi/http-errorsUsage
HttpError
Base error class for HTTP-like errors with built-in Response conversion.
import { HttpError } from '@whi/http-errors';
// Create an HTTP error
const error = new HttpError(404, 'Resource not found');
// Convert to Response object
const response = error.toResponse();
// Response: { status: 404, body: { "error": "Resource not found" } }
// With additional details
const detailedError = new HttpError(500, 'Database error', {
code: 'DB_CONNECTION_FAILED',
retry: true
});
const response2 = detailedError.toResponse();
// Response body: { "error": "Database error", "code": "DB_CONNECTION_FAILED", "retry": true }MissingFieldError
Specialized error for missing required fields (returns 400 Bad Request).
import { MissingFieldError } from '@whi/http-errors';
const error = new MissingFieldError('email');
// Status: 400
// Message: "Missing required field: email"
// Details: { field: "email" }Creating HttpError from Response
Convert error responses back into HttpError objects.
import { HttpError } from '@whi/http-errors';
// From JSON error response
const response = await fetch('/api/endpoint');
if (!response.ok) {
const error = await HttpError.fromResponse(response);
console.log(error.status); // 404
console.log(error.message); // "Not found"
console.log(error.details); // { ... }
}API
HttpError
Constructor:
new HttpError(status: number, message: string, details?: Record<string, any>)Properties:
status: number- HTTP status codemessage: string- Error messagedetails?: Record<string, any>- Additional error details
Methods:
toResponse(): Response- Converts error to a JSON Response objectstatic fromResponse(response: Response): Promise<HttpError>- Creates HttpError from a Response
MissingFieldError
Constructor:
new MissingFieldError(fieldName: string)Extends HttpError with status 400 and pre-formatted message.
Use Cases
Perfect for:
- Cloudflare Workers - Throw and catch errors that convert to proper HTTP responses
- Edge Functions - Deno, Bun, or any runtime with Web APIs
- API Routes - Standardized error handling for fetch-based applications
- Service Workers - Consistent error responses in PWAs
License
LGPL-3.0
Author
Matthew Brisebois