# DS Express Errors — LLM Reference ## Core Imports import { Errors, AppError, asyncHandler, errorHandler, setConfig, initGlobalHandlers, gracefulHttpClose } from 'ds-express-errors' ## HTTP Presets (via Errors) BadRequest, Unauthorized, PaymentRequired, Forbidden, NotFound, Conflict, UnprocessableContent, TooManyRequests, InternalServerError, NotImplemented, BadGateway, ServiceUnavailable, GatewayTimeout Usage: - next(Errors.Preset(message)) -> forwards error to middleware - throw Errors.Preset(message) -> throws error in async/try blocks ## AppError AppError(message: string, statusCode: number, isOperational: boolean) ## asyncHandler asyncHandler(fn) -> wraps async controller, forwards errors to errorHandler ## Middleware errorHandler -> MUST be last in Express chain ## Global Handlers initGlobalHandlers(options?) options: { closeServer?: Function, onShutdown?: async Function(signal), onCrash?: async Function(err, signal), exitOnUnhandledRejection?: boolean (default true), exitOnUncaughtException?: boolean (default true), maxTimeout?: number (default 10000) } gracefulHttpClose(server) -> returns promise ## Configuration (setConfig) setConfig(options) options: { customLogger?: object { error, warn, info, debug }, customMappers?: Array AppError | undefined>, errorClasses?: { Zod?: any, Joi?: any }, needMappers?: Array<'zod'|'joi'|'mongoose'|'prisma'|'sequelize'|'expressValidator'>, maxLoggerRequests?: number, devEnvironments?: Array, formatError?: Function(err, {req, isDev}) -> object } ## Logger Built-in logger supports: logError, logWarning, logInfo, logDebug Custom logger must implement: error, warn, info, debug ## Environment Behavior NODE_ENV in devEnvironments: show stack, method, url NODE_ENV production (or others): hide stack, only status + message ## Built-in Error Mapping (mapErrorNameToPreset) JWT: JsonWebTokenError, TokenExpiredError, NotBeforeError -> 401 express-validator: FieldValidationError, GroupedAlternativeValidationError, AlternativeValidationError -> 422 express-validator: UnknownFieldsError -> 400 Validation: ZodError (Zod), ValidationError (Joi) -> formatted messages Mongoose: CastError, DuplicateKeyError (11000), ValidationError, MongoServerError -> 400/409/500 JS native: ReferenceError, TypeError -> 500, SyntaxError -> 400/500 ## Prisma Error Codes P2000 -> 400, P2001 -> 404, P2002 -> 409, P2003 -> 400, P2005 -> 400, P2006 -> 400, P2007 -> 400 P2011 -> 400, P2014 -> 400, P2015 -> 404, P2021 -> 500, P2022 -> 500, P2025 -> 404, P2027 -> 500 P1001 -> 503, P1002 -> 503, P1003 -> 500 ## Sequelize Error Codes SequelizeValidationError -> 400 SequelizeUniqueConstraintError -> 409 SequelizeForeignKeyConstraintError -> 409 SequelizeOptimisticLockError -> 409 SequelizeEmptyResultError -> 404 SequelizeDatabaseError -> 500 SequelizeConnectionError -> 503 SequelizeTimeoutError -> 504 ## Usage Patterns # 1. Throwing Presets next(Errors.NotFound('User not found')) throw Errors.BadRequest('Invalid input') # can throw directly # 2. Using AppError throw new AppError('Custom message', 402, true) # 3. Async Controller const handler = asyncHandler(async (req,res,next) => { ... }) # 4. Express Middleware app.use(errorHandler) # must be last # 5. Global Handlers initGlobalHandlers({ closeServer: gracefulHttpClose(server), onShutdown: async(), onCrash: async() }) # 6. Custom Config setConfig({ customLogger, customMappers, needMappers, devEnvironments, formatError }) # 7. Error Response Shape # Development { status, method, url, message, stack } # Production { status, message } # End of LLM Reference