Error Handling
Available Error Classes
All error classes are exported individually for tree-shaking. For details on each status code, see the MDN HTTP Status Reference.
Client Errors (4xx)
| Class | Status | Status Text |
|---|---|---|
BadRequestError | 400 | Bad Request |
UnauthorizedError | 401 | Unauthorized |
PaymentRequiredError | 402 | Payment Required |
ForbiddenError | 403 | Forbidden |
NotFoundError | 404 | Not Found |
MethodNotAllowedError | 405 | Method Not Allowed |
NotAcceptableError | 406 | Not Acceptable |
ProxyAuthenticationRequiredError | 407 | Proxy Authentication Required |
RequestTimeoutError | 408 | Request Timeout |
ConflictError | 409 | Conflict |
GoneError | 410 | Gone |
LengthRequiredError | 411 | Length Required |
PreconditionFailedError | 412 | Precondition Failed |
RequestTooLongError | 413 | Payload Too Large |
RequestUriTooLongError | 414 | URI Too Long |
UnsupportedMediaTypeError | 415 | Unsupported Media Type |
RequestedRangeNotSatisfiableError | 416 | Range Not Satisfiable |
ExpectationFailedError | 417 | Expectation Failed |
ImATeapotError | 418 | I'm a teapot |
MisdirectedRequestError | 421 | Misdirected Request |
UnprocessableEntityError | 422 | Unprocessable Entity |
LockedError | 423 | Locked |
FailedDependencyError | 424 | Failed Dependency |
TooEarlyError | 425 | Too Early |
UpgradeRequiredError | 426 | Upgrade Required |
PreconditionRequiredError | 428 | Precondition Required |
TooManyRequestsError | 429 | Too Many Requests |
RequestHeaderFieldsTooLargeError | 431 | Request Header Fields Too Large |
UnavailableForLegalReasonsError | 451 | Unavailable For Legal Reasons |
Server Errors (5xx)
| Class | Status | Status Text |
|---|---|---|
InternalServerError | 500 | Internal Server Error |
NotImplementedError | 501 | Not Implemented |
BadGatewayError | 502 | Bad Gateway |
ServiceUnavailableError | 503 | Service Unavailable |
GatewayTimeoutError | 504 | Gateway Timeout |
HttpVersionNotSupportedError | 505 | HTTP Version Not Supported |
VariantAlsoNegotiatesError | 506 | Variant Also Negotiates |
InsufficientStorageError | 507 | Insufficient Storage |
LoopDetectedError | 508 | Loop Detected |
NotExtendedError | 510 | Not Extended |
NetworkAuthenticationRequiredError | 511 | Network Authentication Required |
Network Errors
| Class | Description |
|---|---|
NetworkError | Connection refused, DNS failures, timeouts |
Handling Errors with instanceof
typescript
import { typedFetch, NotFoundError, UnauthorizedError, NetworkError } from '@pbpeterson/typed-fetch';
type ExpectedErrors = NotFoundError | UnauthorizedError;
const { response, error } = await typedFetch<User, ExpectedErrors>('/api/users/123');
if (error) {
if (error instanceof NotFoundError) {
console.log('User not found');
const details = await error.json<{ message: string }>();
} else if (error instanceof UnauthorizedError) {
console.log('Please log in');
} else if (error instanceof NetworkError) {
console.log('Network error:', error.message);
} else {
// Server errors (5xx)
console.log('Server error:', error.statusText);
}
}Handling Errors with Type Guards
typescript
import { typedFetch, isHttpError, isNetworkError } from '@pbpeterson/typed-fetch';
const { error } = await typedFetch<User>('/api/users/123');
if (error) {
if (isHttpError(error)) {
// error is narrowed to BaseHttpError
console.log(`${error.name}: ${error.status} ${error.statusText}`);
const body = await error.json();
} else if (isNetworkError(error)) {
// error is narrowed to NetworkError
console.log('Connection failed:', error.message);
}
}Typed Error Bodies
The json<T>() method accepts a type parameter to type the error response body:
typescript
interface ApiError {
message: string;
code: string;
fields?: Record<string, string>;
}
if (error instanceof BadRequestError) {
const details = await error.json<ApiError>();
console.log(details.message); // typed as string
console.log(details.fields); // typed as Record<string, string> | undefined
}Static Properties
Access status codes without creating instances:
typescript
import { NotFoundError, BadRequestError } from '@pbpeterson/typed-fetch';
console.log(NotFoundError.status); // 404 (literal type)
console.log(NotFoundError.statusText); // "Not Found" (literal type)
console.log(BadRequestError.status); // 400