@osskit/fastify-error-handler
is a reusable error handler for Fastify. It helps you manage error responses in a consistent and customizable manner, with built-in support for logging and filtering allowed error properties.
- Handles various error types and provides appropriate HTTP status codes.
- Logs errors with customizable logging function.
- Allows specifying which properties of the error object should be included in the response.
- Works seamlessly with Fastify's error handling mechanism.
Install the package via npm:
npm install @osskit/fastify-error-handler
Or via yarn:
yarn add @osskit/fastify-error-handler
import fastify from 'fastify';
import { fastifyErrorHandler } from '@osskit/fastify-error-handler';
const server = fastify();
server.setErrorHandler(fastifyErrorHandler());
server.get('/', async () => {
// Simulate an error
throw new Error('Test error');
});
server.listen(3000, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
You can customize the error handler by providing a logging function and specifying which properties of the error object should be included in the response.
import fastify from 'fastify';
import { fastifyErrorHandler } from '@osskit/fastify-error-handler';
const server = fastify();
const customLogger = ({ error, request, reply }) => {
console.log('Custom log:', error);
};
const options = {
log: customLogger,
allowedProperties: ['detail', 'type']
};
server.setErrorHandler(fastifyErrorHandler(options));
server.get('/', async () => {
const error = new Error('Test error');
error.detail = 'Detailed error information';
error.type = 'CustomError';
throw error;
});
server.listen(3000, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
The error handler works well with HTTP errors created using libraries like http-errors
.
import fastify from 'fastify';
import createHttpError from 'http-errors';
import { fastifyErrorHandler } from '@osskit/fastify-error-handler';
const server = fastify();
server.setErrorHandler(fastifyErrorHandler());
server.get('/not-found', async () => {
throw createHttpError(404, 'Resource not found');
});
server.listen(3000, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
Returns a Fastify error handler function.
-
log
(optional): A function to log errors. Receives an object witherror
,request
, andreply
properties. -
allowedProperties
(optional): An iterable of property names that are allowed to be included in the error response.
This package is licensed under the MIT License. See the LICENSE file for more details.