# Error Handling — GraphQL

Source: https://www.skillbyai.com/en/graphql/m-errors

> The errors array and errors as data.

## Two kinds of errors

The top-level `errors` array reports problems such as validation failures, authentication errors and unexpected exceptions, each with a `message`, `path` and optional `extensions` (for example a `code`). Because each field resolves independently, a response may contain **partial data** with errors for some fields. Many teams model **expected business errors** (out of stock, invalid coupon) as data in the schema, either as `userErrors` in payloads or as union result types, so clients handle them with types instead of parsing messages. Never expose stack traces or internal messages to clients.

## Partial data and a union result

A response and an alternative schema style (illustrative).

```json
// partial success: the recommendations service failed
{
  "data": { "product": { "name": "Desk lamp", "recommendations": null } },
  "errors": [{
    "message": "Recommendations unavailable",
    "path": ["product", "recommendations"],
    "extensions": { "code": "SERVICE_UNAVAILABLE" }
  }]
}

// schema alternative for expected errors:
// union PlaceOrderResult = OrderPlaced | OutOfStock | PaymentDeclined
```

## Mask unexpected errors

Return a generic message with a request ID to clients and log the details server-side.

**Quiz:** Where should an expected "coupon expired" error usually be modelled?

- [ ] As a stack trace in the response
- [ ] As an HTTP 500
- [ ] Only in server logs
- [x] In the schema, for example as userErrors or a union result type

*Answer:* In the schema, for example as userErrors or a union result type. Expected errors are data.
