@verisure-italy/express-error-handler-middleware
v1.9.1
Published
Express error handler middleware with support for domain-specific errors
Downloads
151
Maintainers
Readme
@verisure-italy/express-error-handler-middleware
Express error handler designed to close the pipeline of the monorepo packages with a consistent, typed, and customizable error response format.
Installation
pnpm add @verisure-italy/express-error-handler-middlewareMain Exports
errorHandler(config)- formatters:
formatValidationError,formatAuthenticationError,formatAuthorizationError,formatNotFoundError,formatGenericError - type guards:
isZodError,isDomainError,isValidationError,isAuthenticationError,isAuthorizationError,isNotFoundError - types:
ErrorHandlerConfig,ErrorResponse,DomainError
ErrorHandlerConfig
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| includeStackTrace | boolean | No | Include details.stack in the response |
| logErrors | boolean | No | Log the error to console.error |
| showDetails | boolean | No | Expose validation details and extra error metadata |
| onError | (error, req, res) => void | Promise<void> | No | Side-effect hook for logging or monitoring |
| skipError | (error, req) => boolean | No | Skip this handler and delegate to the next one |
| formatters | formatter overrides | No | Replace the default formatter for a known error family |
ErrorResponse
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| error | string | Yes | Human-readable error name |
| message | string | Yes | Main error message |
| statusCode | number | Yes | HTTP status code |
| code | string | Yes | Machine-readable error code |
| timestamp | string | Yes | ISO timestamp |
| path | string | No | Request path |
| details | ErrorDetails | No | Validation errors, stack trace, and custom metadata |
Supported Error Families
| Family | Typical source | Output status |
| --- | --- | --- |
| Zod validation | Direct ZodError instances | 422 |
| Router validation | ValidationError from router middleware | 422 |
| Authentication | UnauthorizedError, AuthenticationError | 401 |
| Authorization | ForbiddenError and compatible domain errors | 403 |
| Not found | NotFoundError | 404 |
| Generic domain error | Any error with statusCode and code | Custom |
| Generic error | Any other Error | 500 |
Integration Example
import { errorHandler } from '@verisure-italy/express-error-handler-middleware'
app.use(errorHandler({
logErrors: true,
showDetails: process.env.NODE_ENV !== 'production',
includeStackTrace: process.env.NODE_ENV === 'development',
onError: async (error, req) => {
console.error('API error', {
path: req.path,
method: req.method,
message: error.message,
})
},
}))Notes
- Mount it as the last middleware in the Express app.
- If
res.headersSentis alreadytrue, the handler delegates to the next error handler. onErroris intended for side effects, not for mutating the outgoing payload.
