Skip to main content

500 Error Handling

For handling 500 errors, use the native features of Fastify / Express.

Example

$/api/tasks/controller.ts
import { defineController } from './$relay';
import { createTask } from '$/service/tasks';

export default defineController(() => ({
post: async ({ body }) => {
try {
const task = await createTask(body.label);
return { status: 201, body: task };
} catch (e) {
return { status: 500, body: 'Something broke!' };
}
},
}));
$/service/app.ts
import Fastify, { FastifyServerFactory } from 'fastify';
import { API_BASE_PATH } from '$/service/envValues';
import server from '$/$server';

export const init = (serverFactory?: FastifyServerFactory) => {
const app = Fastify({ serverFactory });
app.addHook('onError', (req, reply, err) => {
console.error(err.stack);
});
server(app, { basePath: API_BASE_PATH });
return app;
};