UNPKG

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.

28 lines (23 loc) 872 B
import { NextFunction } from 'express'; export class ApiError extends Error { public statusCode: number; public status: boolean; constructor(statusCode: number, 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); } } } export const ErrorResponse = ( statusCode: number, message: string, next: NextFunction ) => { const error = new ApiError(statusCode, message); if (typeof next === 'function') { next(error); } else { throw error; } };