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 🙏

© 2025 – Pkg Stats / Ryan Hefner

universal-error-mapper

v1.0.0

Published

Universal error mapper with multilingual support for React, Express, Next.js and other frameworks

Downloads

94

Readme

Universal Error Mapper 🌍

Une librairie TypeScript universelle pour la gestion d'erreurs multilingue dans les applications web et API.

🚀 Fonctionnalités

  • Multilingue : Support français et anglais avec fallback automatique
  • Composants UI : Composants React prêts à l'emploi (ErrorDisplay, ErrorBoundary, ErrorToast, ErrorModal)
  • Intégrations : Support Express, Next.js et autres frameworks
  • Codes d'erreur complets : Tous les codes HTTP 4xx et 5xx standards
  • Double vision : Messages utilisateur clairs + logs développeur détaillés
  • TypeScript : Support complet avec types définis
  • Extensible : Facilement personnalisable et extensible

📦 Installation

npm install universal-error-mapper

🎯 Problème résolu

Côté utilisateur final

  • ❌ Messages d'erreur cryptiques : "500 Internal Server Error"
  • ❌ Pas de solution actionnable
  • ❌ Frustration et perte de confiance

Côté développeur

  • ❌ Gestion d'erreurs dupliquée dans chaque projet
  • ❌ Pas de cohérence entre les équipes
  • ❌ Support client surchargé

Notre solution

  • ✅ Messages clairs et contextualisés
  • ✅ Conseils pratiques pour l'utilisateur
  • ✅ Logs détaillés pour les développeurs
  • ✅ Système unifié et réutilisable

🚀 Utilisation rapide

Core API

import { getErrorMessage, getFormattedMessage } from 'universal-error-mapper';

// Obtenir les détails d'une erreur
const errorInfo = await getErrorMessage('404', { lang: 'fr' });
console.log(errorInfo);
// {
//   severity: 'warning',
//   title: 'Page introuvable',
//   description: 'La ressource que vous cherchez n\'existe pas...',
//   actionUser: 'Vérifiez l\'adresse ou retournez à l\'accueil',
//   actionDev: 'Vérifiez vos routes front/back et les redirections'
// }

// Message formaté pour l'utilisateur
const userMessage = await getFormattedMessage('401', { 
  lang: 'en', 
  env: 'user' 
});
console.log(userMessage);
// "Unauthorized
// You need to log in to access this resource.
// Log in and try again."

// Message formaté pour le développeur
const devMessage = await getFormattedMessage('401', { 
  lang: 'en', 
  env: 'dev' 
});
console.log(devMessage);
// "Unauthorized (401)
// You need to log in to access this resource.
// Action: Check authentication system and tokens."

Composants React

import React from 'react';
import { ErrorDisplay, ErrorBoundary, useErrorMapper } from 'universal-error-mapper';

function MyComponent() {
  const { getError, errorInfo, isLoading } = useErrorMapper();

  const handleError = async () => {
    await getError('404', { lang: 'fr' });
  };

  return (
    <ErrorBoundary language="fr">
      <div>
        <button onClick={handleError}>Tester l'erreur 404</button>

        {errorInfo && (
          <ErrorDisplay
            errorInfo={errorInfo}
            code="404"
            variant="detailed"
            onRetry={() => console.log('Retry')}
          />
        )}
      </div>
    </ErrorBoundary>
  );
}

Composants React

import React from 'react';
import { ErrorDisplay, ErrorBoundary, useErrorMapper } from 'universal-error-mapper';

function MyComponent() {
  const { getError, errorInfo, isLoading } = useErrorMapper();

  const handleError = async () => {
    await getError('404', { lang: 'fr' });
  };

  return (
    <ErrorBoundary language="fr">
      <div>
        <button onClick={handleError}>Tester l'erreur 404</button>

        {errorInfo && (
          <ErrorDisplay
            errorInfo={errorInfo}
            code="404"
            variant="detailed"
            onRetry={() => console.log('Retry')}
          />
        )}
      </div>
    </ErrorBoundary>
  );
}

🔌 Framework Integrations

Express Integration

import express from 'express';
import { createErrorMiddleware } from 'universal-error-mapper';

const app = express();

// Middleware to handle errors with automatic mapping
app.use(createErrorMiddleware({
  language: 'en',
  environment: 'user', // or 'dev' for detailed developer messages
  logErrors: true
}));

// Example route that throws an error
app.get('/test-error', (req, res) => {
  const error = new Error('Resource not found');
  (error as any).status = 404;
  throw error; // Will be automatically mapped to user-friendly message
});

app.listen(3000);

Next.js Integration

// pages/api/test.ts
import { createErrorResponse } from 'universal-error-mapper';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    // Your API logic here...
    throw new Error('Something went wrong');
  } catch (error) {
    return createErrorResponse('500', req, res, {
      language: 'en',
      environment: 'user'
    });
  }
}

Intégration Express

import express from 'express';
import { createErrorMiddleware } from 'universal-error-mapper';

const app = express();

// Middleware de gestion d'erreurs
app.use(createErrorMiddleware({
  language: 'fr',
  environment: 'user',
  logErrors: true
}));

// Vos routes...
app.get('/test', (req, res) => {
  const error = new Error('Resource not found');
  (error as any).status = 404;
  throw error; // Sera automatiquement mappé et formaté
});

Intégration Next.js

// pages/api/test.ts
import { createErrorResponse } from 'universal-error-mapper';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    // Votre logique...
    throw new Error('Something went wrong');
  } catch (error) {
    return createErrorResponse('500', req, res, {
      language: 'fr',
      environment: 'user'
    });
  }
}

📚 API Reference

Core Functions

getErrorMessage(code, options?)

Retourne les détails complets d'une erreur.

const errorInfo = await getErrorMessage('404', { 
  lang: 'fr' // 'en' | 'fr'
});

getFormattedMessage(code, options?)

Retourne un message formaté selon l'environnement.

const message = await getFormattedMessage('401', {
  lang: 'en',
  env: 'user' // 'user' | 'dev'
});

getAvailableCodes(lang?)

Retourne tous les codes d'erreur disponibles.

const codes = await getAvailableCodes('fr');
// ['400', '401', '403', '404', ...]

isCodeValid(code, lang?)

Vérifie si un code d'erreur est valide.

const isValid = await isCodeValid('404', 'en');
// true

Composants React

ErrorDisplay

Affiche une erreur avec différents variants.

<ErrorDisplay
  errorInfo={errorInfo}
  code="404"
  variant="detailed" // 'default' | 'compact' | 'detailed'
  showCode={true}
  onRetry={() => {}}
  onDismiss={() => {}}
/>

ErrorBoundary

Boundary React pour capturer les erreurs.

<ErrorBoundary language="fr">
  <YourApp />
</ErrorBoundary>

ErrorToast

Notification toast pour les erreurs.

<ErrorToast
  errorInfo={errorInfo}
  code="404"
  duration={5000}
  position="top-right"
  onRetry={() => {}}
/>

ErrorModal

Modal pour afficher les erreurs importantes.

<ErrorModal
  errorInfo={errorInfo}
  code="404"
  isOpen={true}
  onClose={() => {}}
  onRetry={() => {}}
/>

useErrorMapper

Hook React pour utiliser la librairie.

const { getError, errorInfo, isLoading, clearError } = useErrorMapper();

🌍 Codes d'erreur supportés

4xx - Erreurs client

  • 400 - Bad Request
  • 401 - Unauthorized
  • 402 - Payment Required
  • 403 - Forbidden
  • 404 - Not Found
  • 405 - Method Not Allowed
  • 406 - Not Acceptable
  • 407 - Proxy Authentication Required
  • 408 - Request Timeout
  • 409 - Conflict
  • 410 - Gone
  • 411 - Length Required
  • 412 - Precondition Failed
  • 413 - Payload Too Large
  • 414 - URI Too Long
  • 415 - Unsupported Media Type
  • 416 - Range Not Satisfiable
  • 417 - Expectation Failed
  • 418 - I'm a teapot
  • 421 - Misdirected Request
  • 422 - Unprocessable Entity
  • 423 - Locked
  • 424 - Failed Dependency
  • 425 - Too Early
  • 426 - Upgrade Required
  • 428 - Precondition Required
  • 429 - Too Many Requests
  • 431 - Request Header Fields Too Large
  • 451 - Unavailable For Legal Reasons

5xx - Erreurs serveur

  • 500 - Internal Server Error
  • 501 - Not Implemented
  • 502 - Bad Gateway
  • 503 - Service Unavailable
  • 504 - Gateway Timeout
  • 505 - HTTP Version Not Supported
  • 506 - Variant Also Negotiates
  • 507 - Insufficient Storage
  • 508 - Loop Detected
  • 510 - Not Extended
  • 511 - Network Authentication Required

🎨 Personnalisation

Ajouter de nouveaux codes d'erreur

// src/errors/errors.en.json
{
  "600": {
    "severity": "warning",
    "title": "Custom Error",
    "description": "This is a custom error for your application.",
    "actionUser": "Please contact support for assistance.",
    "actionDev": "Check custom error handling logic."
  }
}

Personnaliser les composants

<ErrorDisplay
  errorInfo={errorInfo}
  code="404"
  className="my-custom-class"
  variant="detailed"
/>

🧪 Tests

npm test

📈 Roadmap

  • [ ] Support Vue.js
  • [ ] Intégration Sentry/Datadog
  • [ ] Métriques et analytics
  • [ ] Support de plus de langues
  • [ ] CLI pour générer les traductions
  • [ ] Plugin VSCode

🤝 Contribution

Les contributions sont les bienvenues ! N'hésitez pas à :

  1. Fork le projet
  2. Créer une branche feature
  3. Commiter vos changements
  4. Pousser vers la branche
  5. Ouvrir une Pull Request

📄 Licence

ISC

🙏 Remerciements

Merci à tous les contributeurs qui rendent ce projet possible !


Universal Error Mapper - Transformez les erreurs en moments de clarté et de confiance ✨