# Error Handling

This document describes how REST APIs should present errors to clients consuming their services.

When an error occurs in a API, the service should return the error to the calling client in an informative and structured manner. The API should return information about the error in the response body.

## Response Body

When an error occurs, a REST API should respond with an 4xx or 5xx [HTTP status code](https://docs.devland.is/technical-overview/api-design-guide/rest-response) and the response should contain a Problem Details object as described in the [IETF RFC7807 documentation](https://datatracker.ietf.org/doc/html/rfc7807).

### Problem Details Object

For REST APIs the Problem Details object is modelled as a JSON object. The format is identified with the `application/problem+json` content type in the HTTP `Content-Type` header.

The `type` string is the primary problem identifier and is, as such, required. Every other field is optional but it is **HIGHLY RECOMMENDED** to at least have `title` and `status` strings present in the error response.

* `type` *(string)* A URI reference that identifies the problem type. This specification encourages that, when dereferenced, it provides human-readable documentation for the problem type.
* `title` *(string)* **(Optional)** A short human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence.
* `status` *(number)* **(Optional)** The HTTP Status Code generated by the origin server for this occurrence of the problem.
* `detail` *(string)* **(Optional)** A human-readable explanation of the problem. This MAY differ from occurrence to occurrence.
* `instance` *(string)* **(Optional)** A URI reference that identifies the specific occurrence of the problem.
* `extensions` **(Optional)** Any Problem Detail object can contain custom extensions specific to the REST API.
  * `traceId` *(string)* A very common custom extension used to further clarify the context in which the error occurred.
  * `params` *(Array)* A common custom extension used to indicate which parameters were being used when the error occurred.

### REST Error Response Examples

Simple Response

```javascript
{
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "status": 403,
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc"
}
```

Response With Extensions

```javascript
{
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "status": 403,
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc",
  "traceId": "7kHPSP_X0W1R0fo5h0fG",
  "balance": 30,
  "accounts": [
    {
      "owner": 587,
      "path": "/account/12345"
    },
    {
      "owner": 587,
      "path": "/account/67890"
    }
  ]
}
```
