All jobs

Add API Error Handling to an Express and Sequelize App

Yes. An agent adds a JSON error handler to your Express and Sequelize API: validation errors become 400s, conflicts 409s, unknown routes 404s, with tests, and a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent starts by finding where errors go today, because the answer is nowhere. In a project like the express-main-example app in sequelize/express-example, express/app.js wraps every route handler in makeHandlerAwareOfAsyncErrors, which catches a rejected promise and passes it to next(error), but no error middleware is registered after the routes, so Express's default handler answers with an HTML page and, outside production, the stack trace. express/helpers.js throws a TypeError when :id is not digits, so GET /api/users/abc is a 500. sequelize/models/user.model.js validates username against /^\w{3,}$/ and marks it unique, so POST /api/users with a short name or a taken name rejects with a SequelizeValidationError or SequelizeUniqueConstraintError, and both are 500s too. A route that does not exist gets Express's Cannot GET text. package.json has express 4, body-parser, sequelize 6 and sqlite3, two scripts and no dev dependencies.

It adds express/errors.js with two pieces. A small HttpError class carries a status and an optional details array, and getIdParam throws one with 400 instead of a TypeError, which is the only change to a route's behaviour that is not a status code. The error middleware, registered after the routes, maps a ValidationError from the sequelize package to 400 with one entry per failed field taken from error.errors, its subclass UniqueConstraintError to 409 with the conflicting field named, ForeignKeyConstraintError to 409, anything with a numeric status such as body-parser's entity.parse.failed on malformed JSON to that status, and everything else to 500 with a fixed message and a console.error of the real error. Every answer is JSON of the shape {"error": {"status", "message", "details"}}.

A 404 handler sits between the routes and the error middleware so an unknown path gets the same JSON shape, and the two existing hand-written 400s in each route file, the one for an id in a create body and the one for a mismatched id on update, are left as they are but switched to the same JSON shape so a client parses one format. The update handlers also learn to answer 404 when Model.update touches zero rows, which today returns 200 for an id that does not exist.

The repository has no tests, so the agent adds a test script with Node's built-in node:test and supertest, running npm run setup-example-db first so the SQLite file exists. The tests send a non-numeric id, a two-character username, a duplicate username, malformed JSON and an unknown path, and assert the status and the JSON body of each. It runs them, starts the server with npm start and repeats the same requests with curl for the pull request, and checks that the happy paths in readme.md, listing users and creating one, still answer as before.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add API error handling to this Express and Sequelize app. Read package.json, index.js, express/app.js, express/helpers.js, every file under express/routes, sequelize/index.js, sequelize/extra-setup.js, every model under sequelize/models, sqlite-example-database/setup.js and readme.md first. Add express/errors.js with an HttpError class and an error middleware that answers JSON of the shape {error: {status, message, details}}: Sequelize ValidationError becomes 400 with one detail per failed field, UniqueConstraintError and ForeignKeyConstraintError become 409, an error with a numeric status such as body-parser's malformed JSON keeps that status, and anything else is 500 with a fixed message and the real error logged. Make getIdParam throw an HttpError 400 instead of a TypeError. Add a 404 handler for unknown routes with the same shape, switch the existing 400 responses in the route files to it, and make update answer 404 when no row changed. Register the handlers after the routes in express/app.js. Add a test script using node:test and supertest that covers a bad id, a short username, a duplicate username, malformed JSON and an unknown route. Run the tests, start the server and show the curl output for each case, then 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 that adds express/errors.js and a test/ directory, changes express/app.js, express/helpers.js and the three route files, and adds supertest as a dev dependency with a test script. The description holds a table of request, old status, new status and new body for the five error cases, with the curl output underneath, so a reviewer sees what a client will get before reading the middleware.

The run's record keeps the test run, the server log with the console.error line for the forced 500, and the curl session, so the proof that a short username is now a 400 and not a stack trace is a response in the log.

Before merging, a reviewer decides whether a unique conflict should be 409 or 400, whether to log with something other than console.error, and whether details should expose Sequelize's validator names to clients. The models, the database setup and the happy-path routes are unchanged.

Run it on every API that answers errors with HTML

A team with several Express services on Sequelize starts one run per repository from its own server: one POST /o/{org}/sessions each, with that repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of a second pull request. Each run reads that service's own models and maps the errors they can raise.

After the handler exists, an automation on the Project with a github trigger on pull_request.opened and pull_request.synchronize and the prompt "if this pull request adds a model validation or a route, add a test under test/ that sends the invalid case and asserts the JSON error shape, and run npm test" keeps every new error path covered. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The error cases of an API are the part nobody sends by hand, so a handler written from the Sequelize docs ships with the wrong class names or the wrong status and no one notices until a client parses HTML. The agent sends every bad request to the running server in its own sandbox, reads the body that came back and puts it in the pull request, so the mapping is checked against the library that is installed, not the version remembered.

The sandbox keeps the test output and the curl session with the run, and the pull request cites them. A team can run the same job across each of its Express services at once, each on its own machine with its own record, and review one table per service.

Frequently asked questions

Why is a unique constraint a 409 and a validation failure a 400?

A failed is or allowNull check means the request itself is malformed and will fail the same way every time, which is what 400 says. A taken username is a valid request that conflicts with current state, and 409 tells the client that retrying with different data, not a corrected format, is the fix. In Sequelize the second is a subclass of the first, so the middleware checks UniqueConstraintError before ValidationError.

Why change getIdParam at all?

Because it throws a plain TypeError, and an error middleware cannot tell that one from a TypeError raised by a bug in a handler without matching on the message text. Throwing an HttpError with a 400 status is explicit and needs no string matching. The regex check and the message it carries are unchanged.

Does the handler leak stack traces?

No. The 500 branch sends a fixed message and logs the real error on the server; the 400 and 409 branches send Sequelize's per-field messages, which describe the client's input and not the server's code. Express's default handler, which this replaces, sends the stack in any environment where NODE_ENV is not production.

Why node:test rather than a test framework?

The repository has no dev dependencies and its engines field asks for Node 10 or later. node:test is built into every supported Node release, so the only addition is supertest for sending requests to the app without binding a port. A reviewer who prefers another runner can move the five tests across; they are plain assertions.

More Sequelize jobs

The same job on other stacks

Keep reading