globleerrorhandler
Version:
"Simplify error handling in Express.js using this libarary.🚀"
73 lines (65 loc) • 1.96 kB
JavaScript
/**
* Represents an application-specific error.
* @extends Error
* @class
*/
class AppError extends Error {
/**
* Create an instance of AppError.
* @constructor
* @param {string} message - The error message.
* @param {number} statusCode - The HTTP status code associated with the error.
*/
constructor(message, statusCode) {
super(message);
/**
* The HTTP status code associated with the error.
* @type {number}
*/
this.statusCode = statusCode;
/**
* The status type of the error ('fail' for 4xx, 'error' for 5xx).
* @type {string}
*/
this.status = `${this.statusCode}`.startsWith('4') ? 'fail' : 'error';
/**
* Indicates whether the error is operational (true for AppError instances).
* @type {boolean}
*/
this.isOperational = true;
// Capture the stack trace.
Error.captureStackTrace(this.constructor, this);
}
}
/**
* Creates a global error handling middleware.
* @function
* @param {Object} options - Options for customizing error response.
* @param {boolean} [options.stack=null] - Include the full error stack in the response.
* @param {boolean} [options.onlyPath=null] - Include only the path causing the error in the response.
* @returns {Function} - Express middleware function for handling errors.
*/
function globleHandler({ stack = null, onlyPath = null } = {}) {
return (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (stack || onlyPath) {
res.status(err.statusCode).json({
status: err.status,
message: err.message,
...(onlyPath && { path: err.stack.split('at')[1].trim() }),
...(stack && { stack: err.stack }),
});
} else {
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
}
next();
};
}
module.exports = {
AppError,
globleHandler,
};