Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions src/plugins/errorPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@

// Import Fastify types for plugin typing
import type { FastifyInstance, FastifyPluginAsync } from "fastify";
// Import fastify-plugin to enable plugin encapsulation and reuse
import fp from "fastify-plugin";
// Import the custom error handler utility
import { handleError } from "../utils/errorHandler.js";


/**
* Plugin to register global error handling for Fastify
* Fastify plugin to register global error handling.
*
* - Sets a custom validator compiler (currently a pass-through for TypeBox schemas).
* This can be extended to add custom validation logic if needed.
* - Registers a global error handler that delegates to the custom handleError utility.
*
* @param fastify Fastify instance to decorate
*/
const errorPlugin: FastifyPluginAsync = async (fastify: FastifyInstance) => {
// Handle validation errors from Fastify's validation
// Override Fastify's validator compiler.
// This implementation simply returns the data as-is, assuming TypeBox schemas handle validation.
// Modify this if you need custom validation logic.
fastify.setValidatorCompiler(({ schema }) => {
return (data: unknown) => {
// Fastify will handle validation using TypeBox schemas
return { value: data };
};
});

// Set global error handler
// Register a global error handler for all uncaught errors in Fastify routes and hooks.
// This ensures consistent error responses and logging.
fastify.setErrorHandler((error, request, reply) => {
handleError(error, request, reply);
});
};


// Export the plugin wrapped with fastify-plugin for encapsulation and reuse
export default fp(errorPlugin);