メインコンテンツまでスキップ

500 エラーハンドリング

500 エラーをハンドルするには、fastify / express 固有の機能を使用します。

$/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;
};