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.
BaseError
Section titled “BaseError”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.
Provided Error Classes
Section titled “Provided Error Classes”🚫 BadRequestError
Section titled “🚫 BadRequestError”export class BadRequestError extends BaseError { constructor(message = 'Bad request', code = 'BAD_REQUEST') { super(message, code, 400); }}
🔒 UnauthorizedError
Section titled “🔒 UnauthorizedError”export class UnauthorizedError extends BaseError { constructor(message = 'Unauthorized', code = 'UNAUTHORIZED') { super(message, code, 401); }}
❓ NotFoundError
Section titled “❓ NotFoundError”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.
Built-in Express Error Handler
Section titled “Built-in Express Error Handler”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);
Example Response
Section titled “Example Response”{ "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 theResult
pattern or domain-specific error handling.
Best Practices
Section titled “Best Practices”✅ 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.