Skip to content

Exceptions

GamanJS provides composeException for handling errors that occur during request processing. Exception handlers can be registered globally (all routes) or per-route.

src/modules/app/exceptions/GlobalException.ts
import { composeException } from 'gaman/compose';
export default composeException((error, ctx) => {
console.error(`[Error] ${ctx.path}:`, error.message);
return ctx.send({
error: error.message,
path: ctx.path,
}).error(); // 500
});

composeException takes a callback (error, ctx) => Response and returns an ExceptionHandler.

Register in defineBootstrap via app.mount():

import { defineBootstrap } from 'gaman';
import router from './router';
import GlobalException from './modules/app/exceptions/GlobalException';
defineBootstrap(async (app) => {
// Register global exception handler
app.mount(GlobalException);
app.mount(router);
app.mountServer({ http: 3431 });
});

The global exception handler catches all errors not handled by per-route exception handlers.

Override error handling for specific routes:

import { composeRouter, composeException } from 'gaman/compose';
import PaymentController from './modules/app/controllers/PaymentController';
const PaymentErrorHandler = composeException((error, ctx) => {
// Log to external service
console.error('[Payment Error]', error);
return ctx.send({
error: 'Payment processing failed',
reference: ctx.request.id,
}).error();
});
export default composeRouter((r) => {
r.post('/payment/process', [PaymentController, 'Process'])
.exception(PaymentErrorHandler);
});
Error occurs in handler
Is there a per-route exception handler?
→ Yes: Use per-route handler
→ No: Is there a global exception handler?
→ Yes: Use global handler
→ No: Return default 500 response
src/modules/app/exceptions/GlobalException.ts
import { composeException } from 'gaman/compose';
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public errors?: Record<string, string[]>,
) {
super(message);
}
}
export default composeException((error, ctx) => {
if (error instanceof AppError) {
if (error.errors) {
return ctx.send({
message: error.message,
errors: error.errors
}).unprocessable();
}
return ctx.send({ message: error.message }).build(error.statusCode);
}
// Unknown error
console.error('[Unhandled]', error);
return ctx.send({ message: 'Internal Server Error' }).error();
});

Usage in controller:

async Create(ctx) {
const body = await ctx.json();
if (!body.email) {
throw new AppError('Validation failed', 422, {
email: ['Email is required'],
});
}
// ... logic
}