Automatic Error Throwing
Unlike nativefetch, ofetch automatically throws errors when the response status is 4xx or 5xx:
response.ok after every request.
FetchError Type
When a request fails, ofetch throws aFetchError with detailed information:
FetchError Properties
string
Formatted error message in the format:
[METHOD] "url": status statusText errorMessageExample: [GET] "/api/user": 404 Not Foundnumber | undefined
HTTP status code of the response (e.g., 404, 500)
number | undefined
Alias for
statusstring | undefined
HTTP status text (e.g., “Not Found”, “Internal Server Error”)
string | undefined
Alias for
statusTextany
The parsed response body, same as
response._data. This is particularly useful for API errors that return error details in the response body.FetchRequest
The request URL string or Request object that was used
FetchResponse | undefined
The Response object with the parsed data available as
_data propertyFetchOptions
The resolved request options that were used
Accessing Error Data
Theerror.data property contains the parsed response body, which is useful for API errors:
The
error.data property is the same as error.response._data, providing convenient access to the parsed response body.Ignoring Response Errors
You can disable automatic error throwing using theignoreResponseError option:
boolean
default:"false"
When set to
true, ofetch will not throw errors for 4xx and 5xx responses. Instead, it returns the response normally.Error Status Codes
ofetch throws errors for all status codes between 400 and 599 (inclusive):- 4xx Client Errors: 400-499 (Bad Request, Unauthorized, Forbidden, Not Found, etc.)
- 5xx Server Errors: 500-599 (Internal Server Error, Bad Gateway, Service Unavailable, etc.)
Error Cause
When the underlying fetch operation fails (network error, timeout, etc.), the original error is preserved in thecause property: