# Add Consistent API Error Responses to a Vapor App

Yes. An agent replaces Vapor's default error middleware with one JSON error shape that carries a code, validates request bodies, tests each refusal, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-error-handling/vapor/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts with how errors leave the app today. In a service generated from vapor/template with Fluent, `Sources/App/configure.swift` registers the database and the `CreateTodo` migration and calls `routes(app)`, which mounts `GET /hello` and the `TodoController` at `/todos` with `index`, `create` and `delete`. The only deliberate error is `Abort(.notFound)` when `Todo.find` returns nothing on delete. Everything else is left to the error middleware Vapor installs by default, which answers an `AbortError` with `{"error": true, "reason": "…"}` and anything unexpected with a generic reason and no code, so a client cannot tell a missing todo from a malformed body without reading the text.

Two refusals are hiding in the template's own code. `TodoDTO` declares `title` as `String?` and its `toModel()` only assigns the title when one was sent, while the `Todo` model's `@Field` is a non-optional `String` and the migration created the column as `.required`; a `POST /todos` with `{}` decodes fine and fails at the database. And `req.parameters.get("todoID")` returns `nil` for a path segment that is not a UUID, so `DELETE /todos/not-a-uuid` reads as a missing todo. The agent fixes the first by making `TodoDTO` conform to `Validatable` with a non-empty `title` and calling `TodoDTO.validate(content:)` in `create`, and keeps the second as a not-found but gives it a code.

The middleware itself is one file, `Sources/App/Middleware/APIErrorMiddleware.swift`, an `AsyncMiddleware` that catches what `next.respond(to:)` throws: an `AbortError` keeps its status and gains a `code` derived from it, a `DecodingError` becomes a 400 naming the missing or mistyped key, and anything else becomes a 500 with a fixed reason while `req.logger.report(error:)` keeps the detail in the log, in every environment. The body is one `Content` struct, so every refusal is `{"error": true, "code": "…", "reason": "…"}` with `application/json`. In `configure.swift` the agent resets `app.middleware`, re-adds Vapor's route logging, and adds the new middleware in place of the default error one, so nothing else about the request pipeline moves.

Tests go into the existing suite in `Tests/AppTests`, which uses Swift Testing with `@Suite("App Tests with DB", .serialized)` and a `withApp` helper that migrates and reverts around each test. The agent adds a test per refusal: `DELETE /todos/<fresh UUID>` answers 404 with code `not_found`, `POST /todos` with `{}` answers 400 with the validation code, and each body decodes as the shared error struct. It runs `swift test` in its sandbox against the database the template was generated for, as `.github/workflows/test-template.yml` does inside `swift:6.3-noble` with a Postgres or MySQL service, and quotes the run.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add consistent API error responses to this Vapor app. Read Package.swift, Sources/App/configure.swift, Sources/App/routes.swift, Sources/App/Controllers/TodoController.swift, Sources/App/DTOs/TodoDTO.swift, Sources/App/Models/Todo.swift and the tests first. Write an AsyncMiddleware that turns every thrown error into one JSON body with error, code and reason: AbortError keeps its status, DecodingError becomes 400 naming the key, anything else becomes 500 with a fixed reason and is logged with req.logger.report. Replace Vapor's default error middleware with it in configure.swift and keep route logging. Make TodoDTO Validatable with a required non-empty title and validate it in create. Add tests for the 404 on an unknown todo and the 400 on an empty body, asserting the shared body shape. Run swift test and quote the output. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request with the new `APIErrorMiddleware.swift`, the `Validatable` conformance in `TodoDTO.swift`, the one-line validation call in `TodoController.swift`, the middleware registration in `configure.swift`, and the added tests. The description quotes `swift test` with the new tests passing beside the four the template ships, and shows one body of each refusal as the middleware now writes it.

The run's record keeps the test output and the build, so a reviewer can see the `DecodingError` case was exercised with a real malformed body rather than asserted in prose, and that the 500 path logs through the request logger rather than printing.

Before merging, a reviewer settles the code names, since the agent derived them from the status and the reason, and decides whether clients should see the key name on a 400 in production or only in development.

## Run it on every new Vapor service

A team that starts each service from `vapor new` sends one `POST /o/{org}/sessions` per repository with this body and the repository in `resources`, from a script. Each run reads its own controllers, so a service with more routes gets a test per refusal those routes make, and each opens its own pull request.

Send a `request_id`, a UUID, with each call so a retried request returns the run it already started. Give the key a `webhook_url` and Rush POSTs `run.completed` when a run's turn ends, with `session_url` to read the pull request from; a run whose tests do not pass ends `needs_review` instead.

## Why run it on Rush?

Error handling is the change everyone agrees on and nobody schedules, and the template's optional `title` is the kind of gap that only shows when a client sends a bad body in production. In its own sandbox the agent reads the DTO, the model and the migration together, finds the mismatch, and proves each refusal with a test rather than describing the middleware.

The `swift test` run stays with the run and the pull request quotes it, so the reviewer reads the bodies the middleware writes rather than the code that should write them. Across every Vapor service a team keeps, the same request runs in parallel, one sandbox and one pull request each.

## Frequently asked questions

### Why replace the default error middleware instead of adding one before it?

Because the default one answers first for anything thrown and writes its own body. Resetting `app.middleware` and adding route logging and the new middleware back keeps one place that shapes errors, which is the point of the change.

### Does a 500 leak the error detail?

No. The body carries a fixed reason and a code; the thrown error goes to the request logger through `req.logger.report(error:)`, where it is readable in the log with the request's id.

### What happens to a non-UUID todo id?

It still answers 404, because `req.parameters.get` returns `nil` for a segment that is not a UUID and `Todo.find(nil)` finds nothing. The response now carries `not_found` as its code, which the new test asserts.

### Will this work with MySQL or SQLite as well as Postgres?

Yes. The middleware and the validation sit above Fluent, and the tests use the same `withApp` helper that migrates whichever database `configure.swift` was generated for, the way the template's own workflow runs all three.

## More Vapor jobs

- [Add API Versioning to a Vapor App](https://getrush.ai/run/add-api-versioning/vapor/)
- [Add Background Jobs to a Vapor App from a Linear Issue](https://getrush.ai/run/add-background-jobs/vapor/)
- [Add Caching to a Vapor App](https://getrush.ai/run/add-caching/vapor/)

## The same job on other stacks

- [Add StatusPages Error Handling to a Ktor API](https://getrush.ai/run/add-api-error-handling/ktor/)
- [Add API Error Handling to an Express and Sequelize App](https://getrush.ai/run/add-api-error-handling/sequelize/)
- [Add LLM API Error Handling to a Streamlit App](https://getrush.ai/run/add-api-error-handling/streamlit/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
