npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

api-error-normalizer

v1.0.0

Published

Normalize API errors into a consistent format

Readme

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