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!' };
}
},
}));
- Fastify
- Express
$/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;
};
$/service/app.ts
import express from 'express';
import server from '$/$server';
import { API_BASE_PATH } from '$/service/envValues';
export const init = () => {
const app = express();
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server(app, { basePath: API_BASE_PATH });
return app;
};