UNPKG

node-js-api-response

Version:

Unified API response and error handling for Express.js in TypeScript. This package provides a middleware for consistent API responses and error handling in Express applications, making it easier to manage API responses and errors in a standardized way.

46 lines (45 loc) 1.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseError = void 0; exports.BaseErrorClass = BaseErrorClass; const error_constants_1 = require("../utils/constants/error.constants"); /** * Represents a custom API error with an HTTP status code and a boolean status. * Extends the built-in Error class to provide additional context for API responses. * @template T - Type of additional details included with the error. */ class BaseError extends Error { /** * Creates an instance of BaseError. * * @param statusCode - The HTTP status code for the error. * @param message - The error message. Defaults to 'Internal server error'. * @param errorCode - Optional error code for more specific error identification. */ constructor(statusCode = 500, message = 'Internal server error', errorCode) { super(message); /** * Indicates the status of the response (false for all errors). */ this.status = false; this.statusCode = statusCode; this.name = this.constructor.name; this.errorCode = errorCode; // Maintains proper stack trace (only needed in V8 environments) if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } } exports.BaseError = BaseError; /** * Dynamically creates an error subclass using ErrorDefinitions */ function BaseErrorClass(errorKey) { const { httpCode, message: defaultMessage, errorCode } = error_constants_1.ErrorDefinitions[errorKey]; return class extends BaseError { constructor(messageOverride) { super(httpCode, messageOverride || defaultMessage, errorCode); } }; }