---
url: /runcobo/guide/errors.md
description: >-
  How Runcobo responds to validation failures, unhandled exceptions and unknown
  routes, and how to customize each.
---

# Error Handling

Runcobo distinguishes three kinds of failure:

| Situation | Default response | Customize with |
| --- | --- | --- |
| Invalid input | `422`/`400`/`413`/`415` with a JSON `errors` list | `render_validation_errors` — see [Request Contracts](/guide/contracts#customizing-the-response) |
| Unhandled exception | `500` with `500 Internal Server Error` as plain text | `Runcobo::ErrorHandler.new { ... }` |
| No matching route | `404` with body `404` | `Runcobo::RouteNotFoundHandler.new { ... }` |

## Expected errors: respond explicitly

Errors that are part of your API — "not found", "already taken", "not allowed" — should be ordinary responses, not exceptions:

```crystal
call do
  if post = store.get_post?(id: input.id)
    render_json({id: post.id, title: post.title})
  else
    render_json({error: "post_not_found"}, status_code: 404)
  end
end
```

To turn a specific exception into a response, rescue it inside `call`. Here, a foreign key violation from PostgreSQL means the author doesn't exist:

```crystal
call do
  post = store.create_post(author_id: input.author_id, title: input.title)
  render_json({id: post.id}, status_code: 201)
rescue error : PQ::PQError
  raise error unless error.field_message(:code) == "23503"   # foreign_key_violation
  render_json({error: "author_not_found"}, status_code: 422)
end
```

Re-raise everything you don't handle, so real failures still reach the error handler below.

## Unhandled exceptions

Any exception that escapes an action is caught by `Runcobo::ErrorHandler`, which:

1. logs it once at `error` level, with the request ID, method and path,
2. **discards** everything the action had already set — headers, cookies and buffered output — so half-written responses never reach the client,
3. responds `500 Internal Server Error`, keeping the `X-Request-Id` header so the client can quote it in a bug report.

Exception messages are never sent to the client.

### A custom error body

Pass a block to render your own response. The response has already been reset and its status set to `500`:

```crystal [src/main.cr]
error_handler = Runcobo::ErrorHandler.new do |context, error|
  context.response.content_type = "application/json"
  {error: "internal_error", request_id: context.request.request_id}.to_json(context.response)
end

Runcobo.start(handlers: [
  Runcobo::LogHandler.new,
  error_handler,
  Runcobo::RouteHandler.new,
  Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)
```

You can also change the status — for example, to `503` for a known "maintenance" exception. If the block itself raises, Runcobo logs that too and falls back to the plain-text `500`.

::: info Errors after streaming starts
Once response headers have been sent (for example while streaming a large file), the status can no longer change. In that case the error is logged and the connection is closed so the client sees an incomplete response rather than a silently truncated one.
:::

## Not found

Requests that match no route reach `Runcobo::RouteNotFoundHandler`, which responds `404` with the body `404`. Pass a block for a custom response:

```crystal
not_found = Runcobo::RouteNotFoundHandler.new do |context|
  context.response.status_code = 404
  context.response.content_type = "application/json"
  context.response.print(%({"error":"route_not_found"})) unless context.request.method == "HEAD"
end
```

Put it last in the handler list.
