jsm-exceptions
Version:
A comprehensive TypeScript exception library with HTTP status code support, detailed JSDoc documentation, and backward compatibility. Provides structured error handling for web applications and APIs.
76 lines (75 loc) • 2.4 kB
JavaScript
/**
* @fileoverview Base exception class for all JSM exceptions
* @author dr. Salmi <reevosolutions@gmail.com>
* @since 22-07-2025
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Base exception class that all JSM exceptions should extend.
* Provides a consistent interface and behavior for all exceptions in the library.
*
* @class BaseException
* @extends {Error}
*/
class BaseException extends Error {
/**
* Creates an instance of BaseException.
*
* @param {string} [message='Internal server error'] - The error message
* @param {number} [status=500] - HTTP status code
* @param {Record<string, any>} [context] - Additional context
* @memberof BaseException
*/
constructor(message = 'Internal server error', status, context) {
super(message);
/**
* HTTP status code associated with this exception
* @type {number}
* @default 500
*/
this.status = 500;
// Set the prototype explicitly to maintain instanceof checks
Object.setPrototypeOf(this, new.target.prototype);
// Assign the error class name - use new.target.name for proper inheritance
this.name = new.target.name;
// Set status code
if (status !== undefined) {
Object.defineProperty(this, 'status', { value: status, writable: false });
}
// Set context
this.context = context;
// Set timestamp
this.timestamp = new Date();
// Capture stack trace, excluding the constructor call
if (Error.captureStackTrace) {
Error.captureStackTrace(this, new.target);
}
}
/**
* Returns a JSON representation of the exception
*
* @returns {object} JSON representation
* @memberof BaseException
*/
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
context: this.context,
timestamp: this.timestamp.toISOString(),
stack: this.stack
};
}
/**
* Returns a string representation of the exception
*
* @returns {string} String representation
* @memberof BaseException
*/
toString() {
return `${this.name} [${this.status}]: ${this.message}`;
}
}
exports.default = BaseException;
;