Skip to content

JSON Errors ​

One error handler that turns every error thrown by a route into a JSON body with the error's status.

ts
import {
    App,
    AppError,
    defineCoreHandler,
    defineErrorHandler,
} from 'routup';

export const app = new App();

app.get('/validate', defineCoreHandler(() => {
    throw new AppError({ status: 422, message: 'Name is required' });
}));

app.get('/crash', defineCoreHandler(() => {
    throw new Error('boom');
}));

app.use(defineErrorHandler((error, event) => {
    event.response.status = error.status;

    return {
        error: {
            status: error.status,
            message: error.message,
        },
    };
}));

Try It ​

Install routup, serve the app from a second file and start it with your runtime as on the Quickstart:

typescript
import { serve } from 'routup';
import { app } from './app.ts';

serve(app, { port: 3000 });
bash
curl http://localhost:3000/validate
# {"error":{"status":422,"message":"Name is required"}}

curl http://localhost:3000/crash
# {"error":{"status":500,"message":"boom"}}

curl http://localhost:3000/unknown
# {"status":404,"message":"Not Found"}

How It Works ​

  • An error handler runs only while an error is pending, and only if it comes after the handler that threw. Registering it after the routes puts it there. See Error Handling.
  • The error argument is always an AppError. A thrown Error is wrapped with status 500 and its message, so the handler sends the message of unexpected errors too. A production app replaces the message of 500 errors.
  • event.response.status sets the status of the response built from the return value. See Status and Headers.
  • An unknown path raises no error, so the error handler does not run. The App answers with its 404 fallback.