@dev-abhi/errorify
Version:
A utility package for simplified error handling and management in Node.js applications.
34 lines (33 loc) • 1.31 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomError = void 0;
const errorCodes_1 = require("../utils/errorCodes");
class CustomError extends Error {
constructor(message = "Internal Server Error", statusCode = 500, errorCode = errorCodes_1.ErrorCodes.INTERNAL_SERVER_ERROR, details) {
super(message);
this.statusCode = statusCode;
this.errorCode = errorCode;
this.details = details;
// Automatically decide whether to include stack trace based on NODE_ENV
this.includeStackTrace = process.env.NODE_ENV === "development";
// Optionally capture the stack trace
if (this.includeStackTrace) {
this.stackTrace = this.stack;
}
}
// Serialize error to JSON format (for API response)
toJSON() {
const errorResponse = {
message: this.message,
statusCode: this.statusCode,
errorCode: this.errorCode,
details: this.details,
};
// If stack trace is available and should be included, add it to the response
if (this.includeStackTrace && this.stackTrace) {
errorResponse.stackTrace = this.stackTrace;
}
return errorResponse;
}
}
exports.CustomError = CustomError;