Skip to content

Error Handling Classes

DomusJS provides a set of structured error classes that help you manage predictable failures, especially in the infrastructure and API layers.

✅ These errors are designed for use outside the domain layer — mainly in HTTP controllers, services, and external integrations.
✅ Inside the domain layer, you should use the Result pattern or domain-specific error objects.


All infrastructure errors extend the BaseError class:

export abstract class BaseError extends Error {
public readonly name: string;
public readonly code: string;
public readonly statusCode: number;
constructor(message: string, code: string, statusCode: number) {
super(message);
this.name = this.constructor.name;
this.code = code;
this.statusCode = statusCode;
Error.captureStackTrace(this, this.constructor);
}
}

✅ Provides a common structure with name, code, and HTTP status.


export class BadRequestError extends BaseError {
constructor(message = 'Bad request', code = 'BAD_REQUEST') {
super(message, code, 400);
}
}
export class UnauthorizedError extends BaseError {
constructor(message = 'Unauthorized', code = 'UNAUTHORIZED') {
super(message, code, 401);
}
}
export class NotFoundError extends BaseError {
constructor(message = 'Resource not found', code = 'NOT_FOUND') {
super(message, code, 404);
}
}

✅ These are intended for invalid inputs, authentication failures, or missing resources in the infrastructure layer.


DomusJS provides a ready-to-use Express middleware called errorHandler that automatically:

✅ Catches thrown BaseError instances.
✅ Logs the error using the registered Logger.
✅ Formats a structured HTTP response.

import { errorHandler } from '@domusjs/infrastructure';
app.use(errorHandler);
{
"code": "NOT_FOUND",
"message": "User not found"
}

✅ For unknown or unhandled errors, it returns a 500 Internal Server Error.

Note: This middleware is for the infrastructure and API layer.
Domain-level logic should use the Result pattern or domain-specific error handling.


✅ Use structured errors to standardize API responses.
✅ Avoid throwing exceptions inside the domain layer — use domain results or notifications.
✅ Centralize error handling using the provided middleware.
✅ Include error codes for better debugging and client feedback.