FetchResponseError
An error representing a response with a failure status code (4XX or 5XX).
constructor()
Creates a new FetchResponseError
instance.
new FetchResponseError<Schema, Method, Path>(request, response);
Arguments:
-
request:
FetchRequest
The fetch request that caused the error.
-
response:
FetchResponse
The fetch response that caused the error.
Type arguments:
-
Schema:
HttpSchema
The HTTP schema used for the fetch instance.
-
Method:
string
The HTTP method of the request that caused the error. Must be one of the methods of the path defined in the schema.
-
Path:
string
The path of the request that caused the error. Must be one of the paths defined in the schema.
import { HttpSchema } from '@zimic/http';
import { createFetch } from '@zimic/fetch';
interface User {
id: string;
username: string;
}
type Schema = HttpSchema<{
'/users/:userId': {
GET: {
response: {
200: { body: User };
404: { body: { message: string } };
};
};
};
}>;
const fetch = createFetch<Schema>({
baseURL: 'http://localhost:3000',
});
const response = await fetch(`/users/${userId}`, {
method: 'GET',
});
if (!response.ok) {
console.log(response.error); // FetchResponseError<Schema, 'GET', '/users'>
}
error.toObject()
Converts the error into a plain object. This method is useful for serialization, debugging, and logging purposes.
error.toObject();
error.toObject(options);
Arguments:
-
options
:FetchResponseErrorObjectOptions
The options for converting the error. By default, the body of the request and response will not be included.
-
includeRequestBody
:boolean | undefined
(defaultfalse
)Whether to include the body of the request in the plain object.
-
includeResponseBody
:boolean | undefined
(defaultfalse
)Whether to include the body of the response in the plain object.
-
Returns: FetchResponseErrorObject
A plain object representing this error. If options.includeRequestBody
or options.includeResponseBody
is true
, the
body of the request and response will be included, respectively, and the return is a Promise
. Otherwise, the return is
the plain object itself without the bodies.
const fetch = createFetch<Schema>({
baseURL: 'http://localhost:3000',
});
const response = await fetch(`/users/${userId}`, {
method: 'GET',
});
if (!response.ok) {
const plainError = response.error.toObject();
console.log(JSON.stringify(plainError));
// {"name":"FetchResponseError","message":"...","request":{...},"response":{...}}
}