Normalize API errors into a consistent format
npm install api-error-normalizerbash
npm install api-error-normalizer
`
Or with yarn:
`bash
yarn add api-error-normalizer
`
Or with pnpm:
`bash
pnpm add api-error-normalizer
`
Quick Start
$3
`typescript
import { normalizeError } from 'api-error-normalizer';
// Normalize any error
const error = new Error('Something went wrong');
const normalized = normalizeError(error);
console.log(normalized);
// Output:
// {
// status: 500,
// code: 'Error',
// message: 'Something went wrong'
// }
`
$3
`typescript
import express from 'express';
import { errorNormalizerMiddleware } from 'api-error-normalizer';
const app = express();
// Your routes here
app.get('/api/users', (req, res) => {
throw new Error('Database connection failed');
});
// Error handling middleware (must be last)
app.use(errorNormalizerMiddleware);
app.listen(3000, () => console.log('Server running on port 3000'));
`
API Reference
$3
Normalizes any error into a standard format.
Parameters:
- error (any) - The error to normalize. Can be:
- Error objects
- Plain objects with error properties
- Strings
- Custom error classes
- null or undefined
- options (NormalizerOptions, optional):
- env (string) - Environment mode ('development' or 'production'). In development, includes stack traces
- log (function) - Custom logging function for error tracking
Returns:
NormalizedError object with:
- status (number) - HTTP status code (default: 500)
- code (string) - Error code/name (default: 'UNKNOWN_ERROR')
- message (string) - Human-readable error message
- details (any, optional) - Additional error details or metadata
Example:
`typescript
import { normalizeError } from 'api-error-normalizer';
// Normalize built-in Error
const error1 = normalizeError(new Error('User not found'));
// Normalize custom object
const error2 = normalizeError({
code: 'VALIDATION_ERROR',
message: 'Invalid email format',
status: 400,
details: { field: 'email' }
});
// Normalize with options
const error3 = normalizeError(error1, {
env: 'development',
log: (err) => console.error('Error logged:', err)
});
`
$3
Express error handling middleware that catches and normalizes errors.
Usage:
`typescript
app.use(errorNormalizerMiddleware);
`
Must be registered after all other middleware and route handlers.
Error Format
All normalized errors follow this consistent structure:
`typescript
interface NormalizedError {
status: number; // HTTP status code (200-599)
code: string; // Error code/type identifier
message: string; // Human-readable message
details?: any; // Optional additional data
}
`
Examples
$3
`typescript
import { normalizeError } from 'api-error-normalizer';
try {
// Database operation
await db.query('SELECT * FROM users WHERE id = ?', [userId]);
} catch (error) {
const normalized = normalizeError(error, {
env: process.env.NODE_ENV
});
res.status(normalized.status).json({ error: normalized });
}
`
$3
`typescript
class ValidationError extends Error {
constructor(message: string, public fields: Record) {
super(message);
this.name = 'ValidationError';
}
}
const error = new ValidationError('Validation failed', {
email: 'Invalid email format',
password: 'Too short'
});
const normalized = normalizeError(error);
// {
// status: 500,
// code: 'ValidationError',
// message: 'Validation failed'
// }
`
$3
`typescript
import express from 'express';
import { errorNormalizerMiddleware } from 'api-error-normalizer';
const app = express();
// Routes
app.get('/api/data', async (req, res) => {
try {
const data = await fetchData();
res.json(data);
} catch (error) {
next(error); // Pass to error handler
}
});
// Global error handler
app.use((err: any, req: any, res: any, next: any) => {
errorNormalizerMiddleware(err, req, res, next);
});
app.listen(3000);
`
TypeScript Support
This library includes complete TypeScript definitions:
`typescript
import type { NormalizedError, NormalizerOptions } from 'api-error-normalizer';
const handleError = (error: unknown, options?: NormalizerOptions): NormalizedError => {
return normalizeError(error, options);
};
`
Options
$3
`typescript
interface NormalizerOptions {
env?: 'development' | 'production';
log?: (error: NormalizedError, req?: Request) => void;
}
`
- env: Controls whether stack traces are included in the normalized error
- 'development': Includes full error details and stack traces
- 'production': Minimal error information for security
- log: Custom logging function for error tracking and monitoring
- Useful for integrating with logging services (Winston, Bunyan, etc.)
Common HTTP Status Codes
The library maps errors to appropriate HTTP status codes:
| Code | Status | Description |
|------|--------|-------------|
| ValidationError | 400 | Invalid input data |
| NotFoundError | 404 | Resource not found |
| UnauthorizedError | 401 | Authentication required |
| ForbiddenError | 403 | Access denied |
| ConflictError | 409 | Resource conflict |
| InternalServerError | 500 | Server error |
Best Practices
1. Use in Error Handlers - Apply middleware/function at the end of your error handling chain
2. Log Errors - Use the log option to track errors in production
3. Custom Codes - Create custom error classes with meaningful error codes
4. Environment-Aware - Set env` to 'production' in production to hide stack traces