# Handling Errors with an Error Flow

The [*error flow*](https://sevenval.gitbook.io/flat/develop/reference/openapi-4/routing#error-flow) is triggered when certain severe errors occur while processing the flow, or when the [`error` action](https://sevenval.gitbook.io/flat/develop/reference/actions/error) is invoked. It is typically used to produce custom error messages or headers, or set the HTTP status. Another example is augmenting the [access log](https://sevenval.gitbook.io/flat/develop/administration/logging) with [custom log fields](https://sevenval.gitbook.io/flat/develop/cookbook/custom-logging).

In your `swagger.yaml`, point the top-level property `x-flat-error` to a flow file:

```yaml
…
x-flat-error:
  flow: error.xml       # ⬅ error flow
…
```

In this example, we use `error.xml` to format a custom error message:

```markup
<flow>
  <template>
    {
      "CustomError":  {
        "Message": {{ $error/message }},
        "Info": {{ $error/info }}
      }
    }
  </template>
  <set-response-headers>
    {
      "Status": {{ $error/status }},
      "Error-Code": {{ $error/code }}
    }
  </set-response-headers>
</flow>
```

This will ensure that all errors that trigger the error flow will produce a consistent status, error message and headers.

## Triggers

Error triggers are

* [schema violations](https://sevenval.gitbook.io/flat/develop/reference/openapi-7/validation),
* [security violations (JWT)](https://sevenval.gitbook.io/flat/develop/reference/openapi-5/security),
* [request errors](https://sevenval.gitbook.io/flat/develop/reference/actions/request#options),
* or the [`error` action](https://sevenval.gitbook.io/flat/develop/reference/actions/error)

## See also

* [Error Flow](https://sevenval.gitbook.io/flat/develop/reference/openapi-4/routing#error-flow)
* [`$error`](https://sevenval.gitbook.io/flat/develop/reference/variables#usderror)
