JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2
  • Score
    100M100P100Q41710F
  • License MIT

Lightweight TypeScript library to create, manage and log typed, structured errors for Node.js, Express and modern JavaScript apps. Simplify error handling, improve debugging, and keep your API responses clean and consistent.

Package Exports

  • @heleneb1/ts-errors
  • @heleneb1/ts-errors/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@heleneb1/ts-errors) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ts-errors banner

🧱 ts-errors

ts-errors is a lightweight TypeScript library for creating structured, typed errors with style. Perfect for TypeScript, Node.js, Express, and JavaScript applications.

npm version New

npm downloads bundle size GitHub stars Coverage

πŸ“˜ This README is also available in πŸ‡«πŸ‡· French and πŸ‡¬πŸ‡§ English.

Handle HTTP errors painlessly β€” with elegance, strict typing, and a touch of emoji ✨

A minimalist TypeScript library to create, format, and manage HTTP errors with style, structure, and expressiveness. Compatible with JavaScript, Express, and external loggers like winston, pino, etc.


πŸ’‘ Why ts-errors ?

Because errors deserve better than throw new Error("Oops").
ts-errors helps you to:

  • Give meaning to your errors (categories, details, typing)
  • Display them clearly (console, logs, API)
  • Integrate them easily into your stack (Express, Winston, etc.)

Requirements: Node >= 18, TypeScript >= 5


NPM | GitHub

✨ Features

  • βœ… Extensible CustomError class with emoji, statusCode, category, details

  • 🎯 Ready-to-use errors (NotFoundError, UnauthorizedError, etc.)

  • 🎨 Formatted output: compact, colorized, or tabular

  • βš™οΈ Built-in Express middleware

  • πŸ”Œ External logger support (winston, pino, etc.)

  • πŸ“¦ Zero external dependencies

  • 🧠 Strict typing + JS/TS autocompletion


πŸ‘€ Demo


πŸš€ Installation

# With npm
npm install @heleneb1/ts-errors

# Or yarn
yarn add @heleneb1/ts-errors

βš™οΈ Quick Start

TypeScript

import { NotFoundError } from "@heleneb1/ts-errors";

throw NotFoundError("User not found", { userId: 42 });

JavaScript

const { NotFoundError } = require("@heleneb1/ts-errors");

throw NotFoundError("User not found", { userId: 42 });

🧩Using CustomError

import { CustomError } from "@heleneb1/ts-errors";

throw new CustomError("Something went wrong", 500, {
  context: "DB connection",
});

⚠️ Creating a CustomError Correctly

The order of arguments matters!

πŸ’‘ Signature:

new CustomError(
  message: string,                // error text
  statusCode?: number,            // HTTP status code (default 500)
  details?: Record<string, any>   // additional info
)

βœ… Correct example:

throw new CustomError("Joke not found", 404, {
  info: `Joke with id ${id} not found πŸ˜”`, // free text, add anything you want
});

❌ Example to avoid:

// Wrong order β†’ statusCode will be replaced by the details object
throw new CustomError("Joke not found", { jokeId: id }, 404);

πŸ’‘ Tip: You can also pass an object directly:

throw new CustomError({
  message: "Joke not found",
  statusCode: 404,
  details: { jokeId: id },
});

🧰 Express Middleware

import express from "express";
import { errorMiddleware, CustomError } from "@heleneb1/ts-errors";

const app = express();

app.get("/test-error", (req, res, next) => {
  next(new CustomError("Something went wrong!", 400, { route: "/test-error" }));
});

app.use(errorMiddleware);

The errorMiddleware automatically serializes and sends JSON responses to the client.


// Exemple with Sequelize and DB error handling

import { Sequelize } from "sequelize";
import express from "express";
import { errorMiddleware, CustomError } from "@heleneb1/ts-errors";
const app = express();
const sequelize = new Sequelize("sqlite::memory:");

app.get("/db-error", async (req, res, next) => {
  try {
    await sequelize.query("SELECT * FROM jokes");
    res.send("βœ… DB query ok");
  } catch (err) {
    next(
      new CustomError("Database error", 500, {
        category: "DB",
        details: err.message,
      })
    );
  }
});
// simulated route to trigger a DB error
app.get("/db-error-test", (req, res, next) => {
  next(
    new CustomError("Database error", 500, {
      category: "DB",
      details: "Simulated error",
    })
  );
});

// Mount the error middleware
app.use(errorMiddleware);

sortie terminal @heleneb1/ts-errors

Terminal output

sortie client @heleneb1/ts-errors

Client output

{
  "message": "Database error",
  "statusCode": 500,
  "emoji": "πŸ’₯",
  "category": "Server Error",
  "details": {
    "category": "DB",
    "details": "Simulated error"
  }
}

Best practices

Always include statusCode and details in your errors.

Configure global options (showEmoji, colorize, autoLog) according to dev/prod environment.

Use the middleware to centralize error handling.

Frontend errors can be logged using formattedMessage().

Exemples concrets

Express

app.get("/test-error", (req, res, next) => {
  next(new CustomError("Something went wrong!", 400, { route: "/test-error" }));
});

NestJS

@Catch(CustomError)
export class CustomErrorFilter implements ExceptionFilter {
  catch(exception: CustomError, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    response.status(exception.statusCode || 500).json(exception.toJSON());
  }
}

βš™οΈ Global Configuration

import { CustomError } from "@heleneb1/ts-errors";

CustomError.settings = {
  showEmoji: false,
  defaultCompact: true,
  colorize: false,
};
CustomError.config({ showEmoji: true, colorize: true });
CustomError.setLogger(myWinstonLogger, "error");

πŸ”Œ External Logger Integration

import { CustomError } from "@heleneb1/ts-errors";
import winston from "winston";

const logger = winston.createLogger({
  /* config */
});

CustomError.setLogger(logger, "error");

πŸ–ΌοΈ Formatted Output

try {
  throw NotFoundError("Page not found", { url: "/404" });
} catch (err) {
  if (err instanceof CustomError) {
    err.log(); // Affiche l’erreur formatΓ©e dans la console
  }
}

πŸ—ƒοΈ Access as Table or JSON

Each CustomError can be displayed as a table in the console using log() or retrieved as JSON using toJSON().

import { NotFoundError, CustomError } from "@heleneb1/ts-errors";

try {
  throw NotFoundError(undefined, { userId: 42 });
} catch (err) {
  if (err instanceof CustomError) {
    // Display as a table in the console
    err.log();

    // Get the JSON object for API or other usage

    console.log(err.toJSON());
  }
}

image @heleneb1/ts-errors

Console Output example

+----+----------------+------------+----------------+--------------+
|    | Message        | StatusCode | Details        | Category     |
+----+----------------+------------+----------------+--------------+
| ⁉️ | Page not found | 404        | {"url":"/404"} | Client Error |
+----+----------------+------------+----------------+--------------+

In your terminal

image ts-errors

If details are too long, they're truncates in the table and printed bellow.

+----+----------------+------------+-----------------------------------+--------------+
|    | Message        | StatusCode | Details                           | Category     |
+----+----------------+------------+-----------------------------------+--------------+
| ⁉️ | Page not found | 404        | {"url":"/404","detail":"You ca... | Client Error |
+----+----------------+------------+-----------------------------------+--------------+

Details (full):
{
  "url": "/404",
  "detail": "You can add any detail here"
}

In your terminal.

image @heleneb1/ts-errors


⚑ Available Errors

  • BadRequestError
  • UnauthorizedError
  • ForbiddenError
  • NotFoundError
  • ConflictError
  • UnprocessableEntityError
  • TooManyRequestsError
  • InternalServerError
  • ServiceUnavailableError
  • GatewayTimeoutError

πŸ“š CustomError API

PropriΓ©tΓ© Type Description
message string Error message
statusCode number HTTP status code
emoji string Associated Emoji
category string "Client Error" ou "Server Error"
details Record<string, unknown> Additional data

Methods

  • log() β€” prints the formatted error
  • formattedMessage(compact, showEmoji, colorize) β€” returns a styled message
  • toJSON() β€” serializes the error for API responses

🧱 Package Structure

export * from "./CustomError";
export * from "./createError";
export * from "./errorHelpers";
export * from "./middlewares/errorMiddleware";

πŸ§ͺ Tests

npm run test

πŸ“ Changelog

  • 1.0.0 β€” Initial release

πŸ›‘οΈ License

MIT β€” see LICENSE for details. You're free to use and modify this library as you see fit.


✨ Author

Made with ❀️ & TypeScript by HeleneB1 β€” creative technologist & digital art director.