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
π 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
β¨ 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
π Installation
# With npm
npm install @heleneb1/ts-errors
# Or yarn
yarn add @heleneb1/ts-errorsβοΈ Quick Start
π Demo
### TypeScriptimport { NotFoundError } from "ts-errors";
throw NotFoundError("User not found", { userId: 42 });JavaScript
const { NotFoundError } = require("ts-errors");
throw NotFoundError("User not found", { userId: 42 });π§©Using CustomError
import { CustomError } from "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, NotFoundError } from "ts-errors";
const app = express();
app.get("/user/:id", (req, res, next) => {
next(NotFoundError("User not found", { id: req.params.id }));
});
app.use(errorMiddleware);The errorMiddleware automatically serializes and sends JSON responses to the client.
βοΈ Global Configuration
import { CustomError } from "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 "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 "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());
}
}
Console Output example
+----+----------------+------------+----------------+--------------+
| | Message | StatusCode | Details | Category |
+----+----------------+------------+----------------+--------------+
| βοΈ | Page not found | 404 | {"url":"/404"} | Client Error |
+----+----------------+------------+----------------+--------------+In your terminal

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.

β‘ 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 errorformatedMessage(compact, showEmoji, colorize)β returns a styled messagetoJSON()β 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.
β¨ Auteur
Made with β€οΈ & TypeScript by HeleneB1 β creative technologist & digital art director.