Overview
ofetch throws FetchError instances when requests fail. These errors provide detailed information about what went wrong, including the request, response, and status information.
FetchError Class
The main error class thrown by ofetch.
export class FetchError<T = any> extends Error implements IFetchError<T> {
constructor(message: string, opts?: { cause: unknown })
}
export interface FetchError<T = any> extends IFetchError<T> {}
Constructor Parameters:
Error message describing what went wrong
The underlying error that caused this error (error chaining)
Properties:
Inherits all properties from IFetchError interface (see below).
Example:
try {
await ofetch('/api/users/999')
} catch (error) {
if (error instanceof FetchError) {
console.error('Status:', error.status)
console.error('Message:', error.message)
console.error('Data:', error.data)
}
}
IFetchError Interface
Interface defining the structure of fetch errors.
export interface IFetchError<T = any> extends Error {
request?: FetchRequest;
options?: FetchOptions;
response?: FetchResponse<T>;
data?: T;
status?: number;
statusText?: string;
statusCode?: number;
statusMessage?: string;
}
Properties
Error message in format: [METHOD] "url": status statusText errorMessage
The underlying error that caused this error, if available
The original request URL or Request object
response
FetchResponse<T> | undefined
Parsed response data from response._data
HTTP status code from the response
HTTP status text from the response
FetchError messages follow this format:
[METHOD] "url": status statusText errorMessage
Examples:
[GET] "https://api.example.com/users/999": 404 Not Found
[POST] "https://api.example.com/users": 400 Bad Request Validation failed
[GET] "https://api.example.com/data": <no response> Network error
Error Handling
Basic Error Handling
try {
const user = await ofetch('/api/users/123')
} catch (error) {
if (error instanceof FetchError) {
console.error(`HTTP ${error.status}: ${error.statusText}`)
console.error('Response data:', error.data)
}
}
Handling Specific Status Codes
try {
const user = await ofetch('/api/users/123')
} catch (error) {
if (error instanceof FetchError) {
switch (error.status) {
case 404:
console.error('User not found')
break
case 401:
console.error('Unauthorized')
redirectToLogin()
break
case 500:
console.error('Server error')
break
default:
console.error('Request failed:', error.message)
}
}
}
Suppressing Errors
Use ignoreResponseError to prevent errors from being thrown:
const response = await ofetch('/api/users/123', {
ignoreResponseError: true
})
if (response === null) {
// Handle 404 or other errors
}
Using Hooks for Error Handling
Handle errors globally using hooks:
const apiFetch = ofetch.create({
onResponseError({ response, error }) {
if (response.status === 401) {
redirectToLogin()
}
// Log to error tracking
errorTracker.log({
status: response.status,
url: response.url,
data: response._data
})
},
onRequestError({ error }) {
// Network errors, timeouts, etc.
console.error('Request failed:', error)
}
})
Network Errors vs HTTP Errors
Network Errors (triggered in onRequestError):
- Network connectivity issues
- Timeouts
- Aborted requests
- CORS errors
HTTP Errors (triggered in onResponseError):
- 4xx client errors (400, 401, 404, etc.)
- 5xx server errors (500, 502, 503, etc.)
await ofetch('/api/data', {
onRequestError({ error }) {
// Network errors
console.error('Network error:', error.message)
},
onResponseError({ response }) {
// HTTP errors
console.error('HTTP error:', response.status)
}
})
createFetchError
Internal function used to create FetchError instances from a FetchContext.
export function createFetchError<T = any>(
ctx: FetchContext<T>
): IFetchError<T>
This function is used internally by ofetch and typically not needed in application code.
Type Parameters
The type of the response data and error data