UNPKG

@ingeze/api-error

Version:

A TypeScript library for handling HTTP errors in Express, NestJS, and Fastify APIs.

38 lines (37 loc) 1.24 kB
class ErrorHandler extends Error { /** * Creates a new instance of ErrorHandler. * * @param {string} message Descriptive error message. * @param {number} [statusCode=500] HTTP status code (default is 500). * @param {string | NotFoundErrorType | UnauthorizedErrorType | BadRequestErrorType | ForbiddenErrorType | ValidationErrorType} [type='GENERIC_ERROR'] Error type. * @param {Record<string, unknown>=} details Additional error details (optional). */ constructor(message, statusCode = 500, type = "GENERIC_ERROR", details) { super(message); this.success = false; this.statusCode = statusCode; this.type = type; this.message = message ?? "Internal server error"; this.details = details; Error.captureStackTrace(this, this.constructor); } /** * Converts the error instance to a JSON object compatible with the ErrorResponse interface. * * @returns {ErrorResponse} Serializable error object. */ toJSON() { return { success: this.success, type: this.type, statusCode: this.statusCode, message: this.message, ...this.details && { details: this.details } }; } } export { ErrorHandler }; //# sourceMappingURL=error-handler.js.map