node-js-api-response-ts
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.
27 lines (26 loc) • 887 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorResponse = exports.ApiError = void 0;
class ApiError extends Error {
constructor(statusCode, message = 'Internal server error') {
super(typeof message === 'string' ? message : JSON.stringify(message));
this.statusCode = statusCode;
this.status = false;
this.name = this.constructor.name;
// Maintains proper stack trace (only needed in V8 environments)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
exports.ApiError = ApiError;
const ErrorResponse = (statusCode, message, next) => {
const error = new ApiError(statusCode, message);
if (typeof next === 'function') {
next(error);
}
else {
throw error;
}
};
exports.ErrorResponse = ErrorResponse;