UNPKG

@thalorlabs/errors

Version:

Enhanced exception handling system for TypeScript applications with comprehensive error classes and debugging capabilities

83 lines (82 loc) 3.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CustomError = void 0; const types_1 = require("@thalorlabs/types"); /** * Base error class for all ThalorLabs error types with standardized error handling. * * Provides common error properties, HTTP status mapping, and serialization methods. * All custom error classes should extend this base class for consistent error handling. * * @example * throw new CustomError(400, 'Invalid request data', 'req-123', { field: 'email' }); * * // In error handling middleware * const errorResponse = customError.getErrorResponse(); * res.status(customError.statusCode).json(errorResponse); */ class CustomError extends Error { constructor(statusCode, message, requestId, context) { super(message); this.statusCode = statusCode; this.status = statusCode >= 400 ? 'failure' : 'success'; this.timestamp = new Date(); this.requestId = requestId; this.context = context; } getStatusText() { // Map status codes to their text representations const statusTextMap = { // 2xx Success [types_1.EHttpSuccessResponse.OK]: 'OK', [types_1.EHttpSuccessResponse.CREATED]: 'CREATED', // 4xx Client Errors [types_1.EHttpClientErrorResponse.BAD_REQUEST]: 'BAD_REQUEST', [types_1.EHttpClientErrorResponse.UNAUTHORIZED]: 'UNAUTHORIZED', [types_1.EHttpClientErrorResponse.FORBIDDEN]: 'FORBIDDEN', [types_1.EHttpClientErrorResponse.NOT_FOUND]: 'NOT_FOUND', [types_1.EHttpClientErrorResponse.UNPROCESSABLE_ENTITY]: 'UNPROCESSABLE_ENTITY', // Additional 4xx status codes 402: 'PAYMENT_REQUIRED', 409: 'CONFLICT', 429: 'TOO_MANY_REQUESTS', 440: 'AUTHENTICATION_TIMEOUT', // 5xx Server Errors [types_1.EHttpServerErrorResponse.INTERNAL_SERVER_ERROR]: 'INTERNAL_SERVER_ERROR', [types_1.EHttpServerErrorResponse.SERVICE_UNAVAILABLE]: 'SERVICE_UNAVAILABLE', // Additional 5xx status codes 501: 'NOT_IMPLEMENTED', 502: 'BAD_GATEWAY', 504: 'GATEWAY_TIMEOUT', }; return statusTextMap[this.statusCode] || 'Unknown'; } toJSON() { return { status: this.status, statusCode: this.statusCode, statusText: this.getStatusText(), message: this.message, timestamp: this.timestamp.toISOString(), requestId: this.requestId, context: this.context, stack: this.stack, }; } getErrorResponse() { const response = { status: this.status, error: this.message, timestamp: this.timestamp.toISOString(), }; if (this.requestId) { response.requestId = this.requestId; } if (this.context) { response.context = this.context; } return response; } } exports.CustomError = CustomError; exports.default = CustomError;