> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/unjs/ofetch/llms.txt
> Use this file to discover all available pages before exploring further.

# FetchError

> Error types and error handling in ofetch

## 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.

```typescript theme={null}
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:**

<ParamField path="message" type="string" required>
  Error message describing what went wrong
</ParamField>

<ParamField path="opts.cause" type="unknown">
  The underlying error that caused this error (error chaining)
</ParamField>

**Properties:**

Inherits all properties from `IFetchError` interface (see below).

**Example:**

```typescript theme={null}
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.

```typescript theme={null}
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

<ParamField path="name" type="string">
  Always `"FetchError"`
</ParamField>

<ParamField path="message" type="string">
  Error message in format: `[METHOD] "url": status statusText errorMessage`
</ParamField>

<ParamField path="cause" type="unknown">
  The underlying error that caused this error, if available
</ParamField>

<ParamField path="request" type="FetchRequest | undefined">
  The original request URL or Request object
</ParamField>

<ParamField path="options" type="FetchOptions | undefined">
  The fetch options used for the request. See [FetchOptions](/api/options/fetch-options).
</ParamField>

<ParamField path="response" type="FetchResponse<T> | undefined">
  The response object if available. See [FetchResponse](/api/types/response-types#fetchresponse).
</ParamField>

<ParamField path="data" type="T | undefined">
  Parsed response data from `response._data`
</ParamField>

<ParamField path="status" type="number | undefined">
  HTTP status code from the response
</ParamField>

<ParamField path="statusText" type="string | undefined">
  HTTP status text from the response
</ParamField>

<ParamField path="statusCode" type="number | undefined">
  Alias for `status`
</ParamField>

<ParamField path="statusMessage" type="string | undefined">
  Alias for `statusText`
</ParamField>

## Error Message Format

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

```typescript theme={null}
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

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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.)

```typescript theme={null}
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.

```typescript theme={null}
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

<ParamField path="T" type="any" default="any">
  The type of the response data and error data
</ParamField>

## Related

* [FetchOptions](/api/options/fetch-options) - Request options including `ignoreResponseError`
* [FetchHooks](/api/options/hooks) - `onRequestError` and `onResponseError` hooks
* [FetchContext](/api/types/response-types#fetchcontext) - Context passed to error hooks
* [FetchResponse](/api/types/response-types#fetchresponse) - Response interface
