The `standard-http-error` package provides a minimalist, extensible JavaScript error class (`HttpError`) specifically designed for representing HTTP status codes. It allows for easy detection of HTTP-related errors using `instanceof` checks within error handling middleware. Currently at version 2.0.1, the core library has not seen updates since 2017, suggesting it is effectively abandoned by its original author, though type definitions are community-maintained. It follows semantic versioning for its major versions. Its key differentiators include its small footprint, direct alignment with standard HTTP status codes (supporting both numeric codes and descriptive names like "NOT_FOUND"), and features for proper error serialization. It offers compatibility with frameworks like Express and Koa by providing non-enumerable aliases for `code` and `message` as `status`, `statusCode`, and `statusMessage` for consistent error object structures.
npm install standard-http-errorVerified import paths — ran on the pinned version, not inferred.
Demonstrates creating `HttpError` instances with numeric codes, named codes, custom messages, and custom properties, and catching them with `instanceof`.
Use the CommonJS `const HttpError = require('standard-http-error');` or the ESM default import `import HttpError from 'standard-http-error';` which Node.js's CJS interop handles.To serialize these specific properties, explicitly copy them to a new object or use a custom serializer. For example: `JSON.stringify({ code: err.code, message: err.message, status: err.status })`.When subclassing with modern `class extends`, ensure `super()` is called correctly and consider explicitly setting `this.name = this.constructor.name;` if needed, although the base `standard-error` library aims to handle this.
If in a CommonJS file, use `const HttpError = require('standard-http-error');`. If in an ES module, use `import HttpError from 'standard-http-error';` to leverage Node.js's CJS-ESM interop.Ensure your module resolution and bundling configuration correctly identifies `standard-http-error` as a CommonJS module. If you are consuming it in an ESM project, use `import HttpError from 'standard-http-error';`.
Access `err.code` and `err.message` directly as they are the primary enumerable properties. If you specifically need the aliases for downstream compatibility, use `(err as any).status` or ensure your type definition explicitly includes these non-enumerable properties.