Overview
Centralized error handling with structured responses.
Features
- Custom error classes
- Production-safe messages
- HTTP exception handling
- Async handler wrapper
Installation
npx hanma add hono-error-handler --framework hono
Dependencies
hono
Code
import { HTTPException } from "hono/http-exception";
import type { ErrorHandler } from "hono";
/**
* Application error class for custom errors
*/
export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 500,
public code?: string,
public details?: unknown
) {
super(message);
this.name = "AppError";
}
}
/**
* Not Found error
*/
export class NotFoundError extends AppError {
constructor(resource = "Resource") {
super(`${resource} not found`, 404, "NOT_FOUND");
}
}
/**
* Validation error
*/
export class ValidationError extends AppError {
constructor(message: string, details?: unknown) {
super(message, 400, "VALIDATION_ERROR", details);
}
}
/**
* Unauthorized error
*/
export class UnauthorizedError extends AppError {
constructor(message = "Unauthorized") {
super(message, 401, "UNAUTHORIZED");
}
}
/**
* Forbidden error
*/
export class ForbiddenError extends AppError {
constructor(message = "Forbidden") {
super(message, 403, "FORBIDDEN");
}
}
/**
* Global error handler
*/
export const errorHandler: ErrorHandler = (err, c) => {
console.error(`[ERROR] ${err.message}`, {
name: err.name,
stack: process.env.NODE_ENV !== "production" ? err.stack : undefined,
});
// Handle HTTPException from Hono
if (err instanceof HTTPException) {
return c.json(
{
success: false,
message: err.message,
code: "HTTP_EXCEPTION",
},
err.status
);
}
// Handle custom AppError
if (err instanceof AppError) {
return c.json(
{
success: false,
message: err.message,
code: err.code,
...(process.env.NODE_ENV !== "production" && { details: err.details }),
},
err.statusCode as any
);
}
// Handle unknown errors
return c.json(
{
success: false,
message:
process.env.NODE_ENV === "production"
? "Internal Server Error"
: err.message,
...(process.env.NODE_ENV !== "production" && { stack: err.stack }),
},
500
);
};
/**
* Async handler wrapper to catch errors in route handlers
*/
export const asyncHandler = <T>(
fn: (c: any) => Promise<T>
): ((c: any) => Promise<T>) => {
return async (c) => {
try {
return await fn(c);
} catch (error) {
throw error; // Let errorHandler catch it
}
};
};
Usage
import { errorHandler, NotFoundError } from './middleware/error-handler';
app.onError(errorHandler);
Dependencies
hono
Frequently Asked Questions
How do I install Error Handler?
Run the following command:
npx hanma add hono-error-handler --framework honoWhat dependencies are required?
This snippet requires: hono. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/middleware/error-handler.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.