error-express
Version:
A lightweight, zero-dependency package to handle global errors in Express.js applications. It catches unhandled errors and provides a simple, yet powerful way to manage them.
643 lines (639 loc) • 24.1 kB
text/typescript
import { Request, Response, NextFunction } from 'express';
/**
* Base application error class that extends the native Error class.
* Used to create standardized application errors with HTTP status codes.
*
* @example
* const error = new AppError('Something went wrong', 500);
*
* @class
* @extends {Error}
*/
declare class AppError extends Error {
message: string;
statusCode: number;
isOparational: boolean;
code: string;
/**
* Creates an AppError instance.
* @param {string} message - The error message
* @param {number} statusCode - The HTTP status code (e.g., 400, 500)
* @param {boolean} [isOparational=true] - Whether this is an operational error that can be handled gracefully
* @param {string} [code] - A short machine-friendly error code (e.g. 'NOT_FOUND')
*/
constructor(message: string, statusCode: number, isOparational?: boolean, code?: string);
}
/**
* Server error class for 5xx HTTP status codes.
* Represents errors that occur on the server side.
*
* @example
* throw new ServerError('Database connection failed');
*
* @class
* @extends {AppError}
*/
declare class ServerError extends AppError {
/**
* Creates a ServerError instance.
* @param {string} message - The error message describing the server error
* @param {number} [statusCode=500] - The HTTP status code (defaults to 500 Internal Server Error)
*/
constructor(message: string, statusCode?: number);
}
/**
* Bad request error class for 400 HTTP status code.
* Represents client request errors with invalid parameters or format.
*
* @example
* throw new BadRequestError('Invalid email format');
*
* @class
* @extends {AppError}
*/
declare class BadRequestError extends AppError {
/**
* Creates a BadRequestError instance.
* @param {string} [message='Bad Request'] - The error message (defaults to standard 400 message)
*/
constructor(message?: string);
}
/**
* Not found error class for 404 HTTP status code.
* Represents when a requested resource cannot be found.
*
* @example
* throw new NotFoundError('User not found');
*
* @class
* @extends {AppError}
*/
declare class NotFoundError extends AppError {
/**
* Creates a NotFoundError instance.
* @param {string} [message='Not Found'] - The error message (defaults to standard 404 message)
*/
constructor(message?: string);
}
/**
* Unauthorized error class for 401 HTTP status code.
* Represents authentication failures or missing credentials.
*
* @example
* throw new UnauthorizedError('Invalid credentials');
*
* @class
* @extends {AppError}
*/
declare class UnauthorizedError extends AppError {
/**
* Creates an UnauthorizedError instance.
* @param {string} [message='Unauthorized'] - The error message (defaults to standard 401 message)
*/
constructor(message?: string);
}
/**
* Forbidden error class for 403 HTTP status code.
* Represents when a user is authenticated but lacks permission to access a resource.
*
* @example
* throw new ForbiddenError('You do not have permission to access this resource');
*
* @class
* @extends {AppError}
*/
declare class ForbiddenError extends AppError {
/**
* Creates a ForbiddenError instance.
* @param {string} [message='Forbidden'] - The error message (defaults to standard 403 message)
*/
constructor(message?: string);
}
/**
* Conflict error class for 409 HTTP status code.
* Represents resource conflicts such as duplicate entries or version conflicts.
*
* @example
* throw new ConflictError('Email already exists');
*
* @class
* @extends {AppError}
*/
declare class ConflictError extends AppError {
/**
* Creates a ConflictError instance.
* @param {string} [message='Conflict'] - The error message (defaults to standard 409 message)
*/
constructor(message?: string);
}
/**
* Unprocessable entity error class for 422 HTTP status code.
* Represents validation errors where the request format is correct but semantically incorrect.
*
* @example
* throw new UnprocessableEntityError('Invalid data provided');
*
* @class
* @extends {AppError}
*/
declare class UnprocessableEntityError extends AppError {
/**
* Creates an UnprocessableEntityError instance.
* @param {string} [message='Unprocessable Entity'] - The error message (defaults to standard 422 message)
*/
constructor(message?: string);
}
/**
* Method not allowed error class for 405 HTTP status code.
* Represents when a request method (GET, POST, etc.) is not allowed for a resource.
*
* @example
* throw new MethodNotAllowedError('POST method not allowed on this endpoint');
*
* @class
* @extends {AppError}
*/
declare class MethodNotAllowedError extends AppError {
/**
* Creates a MethodNotAllowedError instance.
* @param {string} [message='Method Not Allowed'] - The error message (defaults to standard 405 message)
*/
constructor(message?: string);
}
/**
* Not acceptable error class for 406 HTTP status code.
* Represents when the server cannot produce a response matching acceptable media types.
*
* @example
* throw new NotAcceptableError('Requested format not supported');
*
* @class
* @extends {AppError}
*/
declare class NotAcceptableError extends AppError {
/**
* Creates a NotAcceptableError instance.
* @param {string} [message='Not Acceptable'] - The error message (defaults to standard 406 message)
*/
constructor(message?: string);
}
/**
* Request timeout error class for 408 HTTP status code.
* Represents when the server times out waiting for the client request.
*
* @example
* throw new RequestTimeoutError('Request took too long to complete');
*
* @class
* @extends {AppError}
*/
declare class RequestTimeoutError extends AppError {
/**
* Creates a RequestTimeoutError instance.
* @param {string} [message='Request Timeout'] - The error message (defaults to standard 408 message)
*/
constructor(message?: string);
}
/**
* Payload too large error class for 413 HTTP status code.
* Represents when the request body exceeds the server's maximum allowed size.
*
* @example
* throw new PayloadTooLargeError('File size exceeds 10MB limit');
*
* @class
* @extends {AppError}
*/
declare class PayloadTooLargeError extends AppError {
/**
* Creates a PayloadTooLargeError instance.
* @param {string} [message='Payload Too Large'] - The error message (defaults to standard 413 message)
*/
constructor(message?: string);
}
/**
* Unsupported media type error class for 415 HTTP status code.
* Represents when the request body media type is not supported.
*
* @example
* throw new UnsupportedMediaTypeError('application/xml not supported');
*
* @class
* @extends {AppError}
*/
declare class UnsupportedMediaTypeError extends AppError {
/**
* Creates an UnsupportedMediaTypeError instance.
* @param {string} [message='Unsupported Media Type'] - The error message (defaults to standard 415 message)
*/
constructor(message?: string);
}
/**
* Too many requests error class for 429 HTTP status code.
* Represents rate limiting when too many requests are received in a short time.
*
* @example
* throw new TooManyRequestsError('Rate limit exceeded. Please try again later.');
*
* @class
* @extends {AppError}
*/
declare class TooManyRequestsError extends AppError {
/**
* Creates a TooManyRequestsError instance.
* @param {string} [message='Too Many Requests'] - The error message (defaults to standard 429 message)
*/
constructor(message?: string);
}
/**
* Payment required error class for 402 HTTP status code.
* Represents when payment is required to access the resource.
*
* @example
* throw new PaymentRequiredError('Premium subscription required');
*
* @class
* @extends {AppError}
*/
declare class PaymentRequiredError extends AppError {
/**
* Creates a PaymentRequiredError instance.
* @param {string} [message='Payment Required'] - The error message (defaults to standard 402 message)
*/
constructor(message?: string);
}
/**
* Gone error class for 410 HTTP status code.
* Represents when the requested resource is permanently gone and won't be available again.
*
* @example
* throw new GoneError('This resource has been permanently deleted');
*
* @class
* @extends {AppError}
*/
declare class GoneError extends AppError {
/**
* Creates a GoneError instance.
* @param {string} [message='Gone'] - The error message (defaults to standard 410 message)
*/
constructor(message?: string);
}
/**
* Precondition failed error class for 412 HTTP status code.
* Represents when server rejects request due to precondition headers (e.g., If-Match).
*
* @example
* throw new PreconditionFailedError('ETag does not match current version');
*
* @class
* @extends {AppError}
*/
declare class PreconditionFailedError extends AppError {
/**
* Creates a PreconditionFailedError instance.
* @param {string} [message='Precondition Failed'] - The error message (defaults to standard 412 message)
*/
constructor(message?: string);
}
/**
* Not implemented error class for 501 HTTP status code.
* Represents when the server does not support the functionality required to fulfill the request.
*
* @example
* throw new NotImplementedError('This feature is not yet implemented');
*
* @class
* @extends {AppError}
*/
declare class NotImplementedError extends AppError {
/**
* Creates a NotImplementedError instance.
* @param {string} [message='Not Implemented'] - The error message (defaults to standard 501 message)
*/
constructor(message?: string);
}
/**
* Bad gateway error class for 502 HTTP status code.
* Represents when the server received an invalid response from an upstream server.
*
* @example
* throw new BadGatewayError('Upstream server returned invalid response');
*
* @class
* @extends {AppError}
*/
declare class BadGatewayError extends AppError {
/**
* Creates a BadGatewayError instance.
* @param {string} [message='Bad Gateway'] - The error message (defaults to standard 502 message)
*/
constructor(message?: string);
}
/**
* Service unavailable error class for 503 HTTP status code.
* Represents when the server is temporarily unable to handle requests (maintenance, overload, etc.).
*
* @example
* throw new ServiceUnavailableError('Server is under maintenance');
*
* @class
* @extends {AppError}
*/
declare class ServiceUnavailableError extends AppError {
/**
* Creates a ServiceUnavailableError instance.
* @param {string} [message='Service Unavailable'] - The error message (defaults to standard 503 message)
*/
constructor(message?: string);
}
/**
* Gateway timeout error class for 504 HTTP status code.
* Represents when an upstream server fails to respond within the timeout period.
*
* @example
* throw new GatewayTimeoutError('Upstream server did not respond in time');
*
* @class
* @extends {AppError}
*/
declare class GatewayTimeoutError extends AppError {
/**
* Creates a GatewayTimeoutError instance.
* @param {string} [message='Gateway Timeout'] - The error message (defaults to standard 504 message)
*/
constructor(message?: string);
}
/**
* Insufficient storage error class for 507 HTTP status code.
* Represents when the server is unable to store the representation needed to complete the request.
*
* @example
* throw new InsufficientStorageError('Disk quota exceeded');
*
* @class
* @extends {AppError}
*/
declare class InsufficientStorageError extends AppError {
/**
* Creates an InsufficientStorageError instance.
* @param {string} [message='Insufficient Storage'] - The error message (defaults to standard 507 message)
*/
constructor(message?: string);
}
/**
* Processes an error and returns a standardized error response object.
* If the error is an operational AppError, returns its details.
* Otherwise, returns a generic 500 Internal Server Error response.
*
* @param {Error | AppError} err - The error to handle
* @returns {{status: string, statusCode: number, message: string}} Standardized error response object
*
* @example
* const response = handleError(new NotFoundError('User not found'));
* // Returns: { status: 'error', statusCode: 404, message: 'User not found' }
*/
declare const handleError: (err: Error | AppError) => {
status: string;
statusCode: number;
message: string;
code: string;
};
/**
* Express error handling middleware for catching and responding to errors.
* This middleware should be placed at the end of all route handlers and middleware.
* It catches any errors thrown in routes and sends a proper error response.
*
* @param {Error | AppError} err - The error object caught by Express
* @param {Request} _req - Express request object (unused)
* @param {Response} res - Express response object
* @param {NextFunction} _next - Express next function (unused)
*
* @example
* app.use(globalErrorHandler);
*/
declare const globalErrorHandler: (err: Error | AppError, _req: Request, res: Response, _next: NextFunction) => void;
/**
* HTTP Status Codes constant object.
* Contains all standard HTTP status codes organized by category:
* - 1xx: Informational responses
* - 2xx: Successful responses
* - 3xx: Redirection messages
* - 4xx: Client error responses
* - 5xx: Server error responses
*
* @type {Object}
* @readonly
*
* @example
* import { HttpStatusCodes } from './statusCodes';
*
* if (response.statusCode === HttpStatusCodes.NOT_FOUND) {
* console.log('Resource not found');
* }
*/
declare const HttpStatusCodes: {
/** 100 Continue - Client should continue sending the request body */
readonly CONTINUE: 100;
/** 101 Switching Protocols - Server is switching to a different protocol */
readonly SWITCHING_PROTOCOLS: 101;
/** 102 Processing - Server received the request and is processing it */
readonly PROCESSING: 102;
/** 103 Early Hints - Early hints for preloading resources */
readonly EARLY_HINTS: 103;
/** 200 OK - Request succeeded */
readonly OK: 200;
/** 201 Created - Request succeeded and a new resource was created */
readonly CREATED: 201;
/** 202 Accepted - Request has been accepted for processing but not completed */
readonly ACCEPTED: 202;
/** 203 Non-Authoritative Information - Request succeeded but content is from another source */
readonly NON_AUTHORITATIVE_INFORMATION: 203;
/** 204 No Content - Request succeeded but there's no content to send */
readonly NO_CONTENT: 204;
/** 205 Reset Content - Request succeeded and client should reset the view */
readonly RESET_CONTENT: 205;
/** 206 Partial Content - Server sent partial content per range request */
readonly PARTIAL_CONTENT: 206;
/** 207 Multi-Status - Response contains multiple status codes */
readonly MULTI_STATUS: 207;
/** 208 Already Reported - Members already reported in previous binding */
readonly ALREADY_REPORTED: 208;
/** 226 IM Used - Instance manipulation resulted in this representation */
readonly IM_USED: 226;
/** 300 Multiple Choices - Multiple options available for requested resource */
readonly MULTIPLE_CHOICES: 300;
/** 301 Moved Permanently - Resource permanently moved to new URL */
readonly MOVED_PERMANENTLY: 301;
/** 302 Found - Resource temporarily moved to different URL */
readonly FOUND: 302;
/** 303 See Other - Request should be repeated with different method at specified URL */
readonly SEE_OTHER: 303;
/** 304 Not Modified - Resource not modified since last request */
readonly NOT_MODIFIED: 304;
/** 305 Use Proxy - Request must be made through proxy */
readonly USE_PROXY: 305;
/** 307 Temporary Redirect - Resource temporarily moved, repeat request same method */
readonly TEMPORARY_REDIRECT: 307;
/** 308 Permanent Redirect - Resource permanently moved, repeat request same method */
readonly PERMANENT_REDIRECT: 308;
/** 400 Bad Request - Request contains malformed syntax or invalid parameters */
readonly BAD_REQUEST: 400;
/** 401 Unauthorized - Request requires authentication or invalid credentials */
readonly UNAUTHORIZED: 401;
/** 402 Payment Required - Payment required for this resource */
readonly PAYMENT_REQUIRED: 402;
/** 403 Forbidden - Client lacks permission to access the resource */
readonly FORBIDDEN: 403;
/** 404 Not Found - Server cannot find the requested resource */
readonly NOT_FOUND: 404;
/** 405 Method Not Allowed - HTTP method not allowed for this resource */
readonly METHOD_NOT_ALLOWED: 405;
/** 406 Not Acceptable - Server cannot produce acceptable response format */
readonly NOT_ACCEPTABLE: 406;
/** 407 Proxy Authentication Required - Proxy authentication required */
readonly PROXY_AUTHENTICATION_REQUIRED: 407;
/** 408 Request Timeout - Server timed out waiting for request */
readonly REQUEST_TIMEOUT: 408;
/** 409 Conflict - Request conflicts with current state of resource */
readonly CONFLICT: 409;
/** 410 Gone - Requested resource no longer exists and won't be available again */
readonly GONE: 410;
/** 411 Length Required - Request header Content-Length is required */
readonly LENGTH_REQUIRED: 411;
/** 412 Precondition Failed - Precondition in request header not satisfied */
readonly PRECONDITION_FAILED: 412;
/** 413 Payload Too Large - Request body exceeds maximum allowed size */
readonly PAYLOAD_TOO_LARGE: 413;
/** 414 URI Too Long - Request URI exceeds maximum allowed length */
readonly URI_TOO_LONG: 414;
/** 415 Unsupported Media Type - Request media type not supported */
readonly UNSUPPORTED_MEDIA_TYPE: 415;
/** 416 Range Not Satisfiable - Range request cannot be satisfied */
readonly RANGE_NOT_SATISFIABLE: 416;
/** 417 Expectation Failed - Server cannot meet Expect header requirements */
readonly EXPECTATION_FAILED: 417;
/** 418 I'm a teapot - Server is a teapot (April Fools' joke) */
readonly IM_A_TEAPOT: 418;
/** 421 Misdirected Request - Request sent to server that cannot produce response */
readonly MISDIRECTED_REQUEST: 421;
/** 422 Unprocessable Entity - Request semantically incorrect or validation failed */
readonly UNPROCESSABLE_ENTITY: 422;
/** 423 Locked - Resource being accessed is locked */
readonly LOCKED: 423;
/** 424 Failed Dependency - Request failed due to failure of previous request */
readonly FAILED_DEPENDENCY: 424;
/** 425 Too Early - Server unwilling to risk processing prematurely sent request */
readonly TOO_EARLY: 425;
/** 426 Upgrade Required - Client should switch to different protocol */
readonly UPGRADE_REQUIRED: 426;
/** 428 Precondition Required - Server requires conditional request */
readonly PRECONDITION_REQUIRED: 428;
/** 429 Too Many Requests - Client sent too many requests (rate limited) */
readonly TOO_MANY_REQUESTS: 429;
/** 431 Request Header Fields Too Large - Request header fields exceed size limit */
readonly REQUEST_HEADER_FIELDS_TOO_LARGE: 431;
/** 451 Unavailable For Legal Reasons - Resource unavailable for legal reasons */
readonly UNAVAILABLE_FOR_LEGAL_REASONS: 451;
/** 500 Internal Server Error - Generic server error */
readonly INTERNAL_SERVER_ERROR: 500;
/** 501 Not Implemented - Server does not support requested functionality */
readonly NOT_IMPLEMENTED: 501;
/** 502 Bad Gateway - Server received invalid response from upstream server */
readonly BAD_GATEWAY: 502;
/** 503 Service Unavailable - Server temporarily unable to handle requests */
readonly SERVICE_UNAVAILABLE: 503;
/** 504 Gateway Timeout - Upstream server did not respond in time */
readonly GATEWAY_TIMEOUT: 504;
/** 505 HTTP Version Not Supported - Server does not support HTTP version */
readonly HTTP_VERSION_NOT_SUPPORTED: 505;
/** 506 Variant Also Negotiates - Server has internal configuration error */
readonly VARIANT_ALSO_NEGOTIATES: 506;
/** 507 Insufficient Storage - Server unable to store request data */
readonly INSUFFICIENT_STORAGE: 507;
/** 508 Loop Detected - Infinite loop detected in request processing */
readonly LOOP_DETECTED: 508;
/** 510 Not Extended - Further extensions required to process request */
readonly NOT_EXTENDED: 510;
/** 511 Network Authentication Required - Network authentication required */
readonly NETWORK_AUTHENTICATION_REQUIRED: 511;
};
/**
* Default human-readable HTTP status messages mapped by status code.
* Provides standard messages for each HTTP status code.
* Can be used as fallback messages when no custom message is provided.
*
* @type {Object}
* @readonly
*
* @example
* import { DefaultStatusMessages, HttpStatusCodes } from './statusCodes';
*
* const message = DefaultStatusMessages[HttpStatusCodes.NOT_FOUND];
* Result: 'Not Found'
*/
declare const DefaultStatusMessages: {
readonly 100: "Continue";
readonly 101: "Switching Protocols";
readonly 102: "Processing";
readonly 103: "Early Hints";
readonly 200: "OK";
readonly 201: "Created";
readonly 202: "Accepted";
readonly 203: "Non-Authoritative Information";
readonly 204: "No Content";
readonly 205: "Reset Content";
readonly 206: "Partial Content";
readonly 207: "Multi-Status";
readonly 208: "Already Reported";
readonly 226: "IM Used";
readonly 300: "Multiple Choices";
readonly 301: "Moved Permanently";
readonly 302: "Found";
readonly 303: "See Other";
readonly 304: "Not Modified";
readonly 305: "Use Proxy";
readonly 307: "Temporary Redirect";
readonly 308: "Permanent Redirect";
readonly 400: "Bad Request";
readonly 401: "Unauthorized";
readonly 402: "Payment Required";
readonly 403: "Forbidden";
readonly 404: "Not Found";
readonly 405: "Method Not Allowed";
readonly 406: "Not Acceptable";
readonly 407: "Proxy Authentication Required";
readonly 408: "Request Timeout";
readonly 409: "Conflict";
readonly 410: "Gone";
readonly 411: "Length Required";
readonly 412: "Precondition Failed";
readonly 413: "Payload Too Large";
readonly 414: "URI Too Long";
readonly 415: "Unsupported Media Type";
readonly 416: "Range Not Satisfiable";
readonly 417: "Expectation Failed";
readonly 418: "I'm a teapot";
readonly 421: "Misdirected Request";
readonly 422: "Unprocessable Entity";
readonly 423: "Locked";
readonly 424: "Failed Dependency";
readonly 425: "Too Early";
readonly 426: "Upgrade Required";
readonly 428: "Precondition Required";
readonly 429: "Too Many Requests";
readonly 431: "Request Header Fields Too Large";
readonly 451: "Unavailable For Legal Reasons";
readonly 500: "Internal Server Error";
readonly 501: "Not Implemented";
readonly 502: "Bad Gateway";
readonly 503: "Service Unavailable";
readonly 504: "Gateway Timeout";
readonly 505: "HTTP Version Not Supported";
readonly 506: "Variant Also Negotiates";
readonly 507: "Insufficient Storage";
readonly 508: "Loop Detected";
readonly 510: "Not Extended";
readonly 511: "Network Authentication Required";
};
export { AppError, BadGatewayError, BadRequestError, ConflictError, DefaultStatusMessages, ForbiddenError, GatewayTimeoutError, GoneError, HttpStatusCodes, InsufficientStorageError, MethodNotAllowedError, NotAcceptableError, NotFoundError, NotImplementedError, PayloadTooLargeError, PaymentRequiredError, PreconditionFailedError, RequestTimeoutError, ServerError, ServiceUnavailableError, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, UnsupportedMediaTypeError, globalErrorHandler, handleError };