| name | mongez-http-error-handling |
| description | @mongez/http `HttpError` and `HttpResult<T>` — status predicates (`isNotFound`, `isUnauthorized`, `isForbidden`, `isValidationError`, `isRateLimited`, `isClientError`, `isServerError`), runtime flags (`isAborted`, `isTimeout`, `isNetwork`), `toJSON`. `{data, error}` discriminated union; opt-in `throw: true` mode; TypeScript type narrowing.
|
Error handling
HttpError
class HttpError extends Error {
status: number | null
body: unknown
response: Response | null
headers: Record<string, string> | null
request: OutgoingRequest | null
isAborted: boolean
isTimeout: boolean
isNetwork: boolean
get isClientError(): boolean
get isServerError(): boolean
get isUnauthorized(): boolean
get isForbidden(): boolean
get isNotFound(): boolean
get isValidationError(): boolean
get isRateLimited(): boolean
toJSON(): Record<string, unknown>
}
HttpResult
type HttpResult<T> =
| { data: T; error: null; status: number; response: Response; headers: Record<string, string>; request: OutgoingRequest }
| { data: null; error: HttpError; status: number | null; response: Response | null; headers: Record<string, string> | null; request: OutgoingRequest }
Default pattern — destructure result
const { data, error } = await http.get<User>('/users/1');
if (error) {
if (error.isNotFound) console.warn('User not found');
else if (error.isUnauthorized) redirect('/login');
else if (error.isValidationError) showFormErrors(error.body);
else if (error.isAborted) { }
else showGenericError(error.message);
return;
}
console.log(data.name);
Validation errors (422) — Laravel-style
const { data, error } = await usersResource.create(formData);
if (error?.isValidationError) {
const { errors } = error.body as { errors: Record<string, string[]> };
for (const [field, messages] of Object.entries(errors)) {
setFieldError(field, messages[0]);
}
}
Opt-in throw mode
try {
const { data } = await http.get('/users/1', { throw: true });
} catch (err) {
if (err instanceof HttpError && err.isNotFound) {
}
}
Type narrowing
The HttpResult<T> discriminated union narrows automatically:
const result = await http.get<User>('/me');
if (result.error) {
result.data
result.error
} else {
result.data
result.error
result.headers
}