Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

api-error-normalizer

A lightweight, type-safe TypeScript library for normalizing API errors into a consistent, standardized format. Perfect for Express.js applications and REST APIs.

Features

  • Consistent Error Format - Standardize all error responses across your API
  • Type-Safe - Full TypeScript support with comprehensive type definitions
  • Express Middleware - Drop-in middleware for Express applications
  • Flexible - Handle errors from any source (built-in errors, custom objects, strings, etc.)
  • Lightweight - Zero dependencies, minimal bundle size
  • Customizable - Configure error codes, status codes, and error mapping
  • Production-Ready - Includes proper error logging and stack traces

Installation

npm install api-error-normalizer

Or with yarn:

yarn add api-error-normalizer

Or with pnpm:

pnpm add api-error-normalizer

Quick Start

Basic Usage

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'
// }

Express Middleware

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

normalizeError(error, options?)

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:

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)
});

errorNormalizerMiddleware

Express error handling middleware that catches and normalizes errors.

Usage:

app.use(errorNormalizerMiddleware);

Must be registered after all other middleware and route handlers.

Error Format

All normalized errors follow this consistent structure:

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

Handling Database Errors

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 });
}

Custom Error Objects

class ValidationError extends Error {
  constructor(message: string, public fields: Record<string, string>) {
    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'
// }

Global Error Handling

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:

import type { NormalizedError, NormalizerOptions } from 'api-error-normalizer';

const handleError = (error: unknown, options?: NormalizerOptions): NormalizedError => {
  return normalizeError(error, options);
};

Options

NormalizerOptions

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
  5. Type Safety - Always use TypeScript for better type checking

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details.

Changelog

1.0.0

  • Initial release
  • Basic error normalization
  • Express middleware support
  • Full TypeScript support

Support

For issues, questions, or suggestions, please open an issue on GitHub.


Made for better API error handling

About

Lightweight, type-safe TypeScript library for normalizing API and Express errors into consistent responses.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages