generic-errors
raw JSON → 2.3.1 verified Fri May 01 auth: no javascript
Provides error constructors with common HTTP status codes as numeric properties, supporting both Node.js and browser usage. Current stable version is 2.3.1 (last updated with dependency security patches). Release cadence is ad-hoc with occasional minor updates. Key differentiators: includes a stack-trace ponyfill for Safari compatibility, does not pollute stack depth, and offers detection via BaseError.isGenericError even after JSON serialization. Over 40 error types from 4xx and 5xx families are available.
Common errors
error TypeError: errors.NotFound is not a constructor ↓
cause Using require on this package returns an object, not a class directly.
fix
Use: const errors = require('generic-errors'); const notFound = new errors.NotFound();
error import errors from 'generic-errors'; // SyntaxError: The requested module 'generic-errors' does not provide an export named 'default' ↓
cause No default ESM export.
fix
Use named import: import { NotFound, BadRequest } from 'generic-errors';
error Uncaught Error: toString() failed ↓
cause Instantiating without 'new' (e.g., errors.NotFound()).
fix
Always use 'new errors.NotFound()'.
Warnings
breaking v2.0.0 changed from exporting a single Error object to an object with named constructors. ↓
fix Update imports: const errors = require('generic-errors'); const notFound = new errors.NotFound();
deprecated Direct construction without 'new' is deprecated and may break in future. ↓
fix Always use 'new errors.SomeError()'.
gotcha Error properties may be lost if you serialize via JSON.stringify without custom toJSON. ↓
fix Use the built-in toJSON or implement your own serialization.
gotcha Some constructors like Teapot (418) are humorous but real HTTP status codes. ↓
fix Do not rely on all listed codes being widely recognized.
Install
npm install generic-errors yarn add generic-errors pnpm add generic-errors Imports
- NotFound wrong
const { NotFound } = require('generic-errors');correctconst errors = require('generic-errors'); const notFound = new errors.NotFound('message'); - BaseError wrong
const BaseError = require('generic-errors').BaseError;correctimport { BaseError } from 'generic-errors'; - BadRequest wrong
import BadRequest from 'generic-errors';correctconst { BadRequest } = require('generic-errors');
Quickstart
const errors = require('generic-errors');
try {
throw new errors.NotFound('Resource not found');
} catch (err) {
console.log(err.message); // 'Resource not found'
console.log(err.statusCode); // 404
console.log(err instanceof errors.BaseError); // true
}
// With additional properties
const err2 = new errors.Unprocessable({ message: 'Validation failed', fields: ['email'] });
console.log(err2.fields); // ['email']
// Detection after serialization
const serialized = JSON.parse(JSON.stringify(err2));
console.log(errors.BaseError.isGenericError(serialized)); // true