Security News
Node.js EOL Versions CVE Dubbed the "Worst CVE of the Year" by Security Experts
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
standard-http-error
Advanced tools
Standard HTTP error class. Proper serialization, no bloat. Extensible.
The standard-http-error npm package provides a simple way to create and manage HTTP errors in Node.js applications. It standardizes the creation of HTTP error objects, making it easier to handle errors consistently across your application.
Creating HTTP Error Instances
This feature allows you to create an instance of an HTTP error with a specific status code and message. The code sample demonstrates creating a 404 Not Found error.
const HttpError = require('standard-http-error');
const error = new HttpError(404, 'Not Found');
console.log(error.status); // 404
console.log(error.message); // 'Not Found'
Custom Error Messages
You can customize the error message for any HTTP status code. The code sample shows how to create a 500 Internal Server Error with a custom message.
const HttpError = require('standard-http-error');
const error = new HttpError(500, 'Internal Server Error');
console.log(error.status); // 500
console.log(error.message); // 'Internal Server Error'
Default Error Messages
If no custom message is provided, the package uses default messages for standard HTTP status codes. The code sample demonstrates creating a 400 Bad Request error with the default message.
const HttpError = require('standard-http-error');
const error = new HttpError(400);
console.log(error.status); // 400
console.log(error.message); // 'Bad Request'
The http-errors package is a popular alternative that provides a similar functionality of creating HTTP error objects. It offers a more extensive set of features, including the ability to create custom error types and attach additional properties to error objects. Compared to standard-http-error, http-errors is more feature-rich and widely used in the Node.js community.
The create-error package allows developers to create custom error types with ease. It is similar to standard-http-error in that it simplifies error handling, but it focuses more on creating custom error types rather than standard HTTP errors. It is useful for applications that require a more tailored error handling approach.
StandardHttpError.js is a very simple but useful error class for
JavaScript and Node.js that represents HTTP errors. You can then detect it with
instanceof
in error handling middleware and act accordingly. Also works in the
browser through Browserify.
You can use StandardHttpError.js with any error code you like, standardized or
not. They don't have to exist beforehand, so if you're living on the cutting
edge, feel free to use new HttpError(451, "Unavailable For Legal Reasons")
.
npm install standard-http-error
StandardHttpError.js follows semantic versioning, so feel
free to depend on its major version with something like >= 1.0.0 < 2
(a.k.a ^1.0.0
).
var HttpError = require("standard-http-error")
throw new HttpError(404)
Your error handler will then receive an instance of HttpError
along with the
following enumerable properties:
Property | Value |
---|---|
name | "HttpError" |
code | 404 |
message | "Not Found" |
As always for errors, the non-enumerable stack
property is there as well.
For compatibility with Express or Koa's default request handler (the one that
prints your errors out if you don't handle them), StandardHttpError.js also sets
status
, statusCode
and statusMessage
to be aliases of code
and
message
. They're non-enumerable to not pollute serialization.
StandardHttpError.js also supports passing a constant name instead of the error code.
new HttpError("NOT_FOUND")
new HttpError("FORBIDDEN")
See below for a list of error code names.
new HttpError(412, "Bad CSRF Token")
The default "Precondition Failed" message that the error code 412 would've resulted in will then be replaced by "Bad CSRF Token".
Note that status messages were always meant to be human readable, so it's perfect fine and even preferable to provide clarification in the status message. Try to stick to the capitalized form, though, as that will match the default HTTP status message style.
You can pass custom properties to be attached to the error instance as an object:
new HttpError(404, {url: req.url})
new HttpError(412, "Bad CSRF Token", {session: req.session})
You can access the given session
property then as err.session
.
If you wish to add your own functionality to StandardHttpError, subclass it:
var HttpError = require("standard-http-error")
function RemoteError(res) {
HttpError.call(this, res.statusCode, res.statusMessage)
}
RemoteError.prototype = Object.create(HttpError.prototype, {
constructor: {value: RemoteError, configurable: true, writeable: true}
})
The StandardError.js library that
StandardHttpError.js uses makes sure the name
and stack
properties of your
new error class are set properly.
If you don't want your new error class to directly inherit from
StandardHttpError
, feel free to leave the RemoteError.prototype
line out.
Everything will work as before except your RemoteError
will no longer be an
instanceof
StandardHttpError.js. You might want to manually grab the
HttpError.prototype.toString
function then though, as that's useful for nice
String(err)
output.
switch (err.code) {
case HttpError.UNAUTHORIZED: return void res.redirect("/signin")
case HttpError.NOT_FOUND: return void res.render("404")
case 451: return void res.redirect("/legal")
default: return void res.render("500")
}
StandardHttpError.js comes very handy when used with Connect/Express's error handling functionality:
var HttpError = require("standard-http-error")
var app = require("express")()
app.get("/account", function(req, res, next) {
if (req.account == null) throw new HttpError(401)
if (req.account.budget == 0) throw new HttpError(402)
// ...
})
app.use(function(err, req, res, next) {
if (!(err instanceof HttpError)) return void next(err)
res.statusCode = err.code
res.statusMessage = err.message
res.render("error", {title: err.message})
})
Error Codes
-----------
StandardHttpError.js comes with a list of status message constants that you can
use for comparison and in `switch` statements.
HttpError.NOT_FOUND // => 404
When running on Node.js, cached status codes and their names get merged with new
codes from Http.STATUS_CODES
. Existing status codes will not be changed
without bumping StandardHttpError.js's major version number. That ensures
consistent constants in Node and in the browser.
Code | Name |
---|---|
100 | CONTINUE |
101 | SWITCHING_PROTOCOLS |
102 | PROCESSING |
200 | OK |
201 | CREATED |
202 | ACCEPTED |
203 | NON_AUTHORITATIVE_INFORMATION |
204 | NO_CONTENT |
205 | RESET_CONTENT |
206 | PARTIAL_CONTENT |
207 | MULTI_STATUS |
208 | ALREADY_REPORTED |
226 | IM_USED |
300 | MULTIPLE_CHOICES |
301 | MOVED_PERMANENTLY |
302 | MOVED_TEMPORARILY |
303 | SEE_OTHER |
304 | NOT_MODIFIED |
305 | USE_PROXY |
307 | TEMPORARY_REDIRECT |
308 | PERMANENT_REDIRECT |
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_TIME_OUT |
409 | CONFLICT |
410 | GONE |
411 | LENGTH_REQUIRED |
412 | PRECONDITION_FAILED |
413 | REQUEST_ENTITY_TOO_LARGE |
414 | REQUEST_URI_TOO_LARGE |
415 | UNSUPPORTED_MEDIA_TYPE |
416 | REQUESTED_RANGE_NOT_SATISFIABLE |
417 | EXPECTATION_FAILED |
418 | IM_A_TEAPOT |
421 | MISDIRECTED_REQUEST |
422 | UNPROCESSABLE_ENTITY |
423 | LOCKED |
424 | FAILED_DEPENDENCY |
425 | UNORDERED_COLLECTION |
426 | UPGRADE_REQUIRED |
428 | PRECONDITION_REQUIRED |
429 | TOO_MANY_REQUESTS |
431 | REQUEST_HEADER_FIELDS_TOO_LARGE |
500 | INTERNAL_SERVER_ERROR |
501 | NOT_IMPLEMENTED |
502 | BAD_GATEWAY |
503 | SERVICE_UNAVAILABLE |
504 | GATEWAY_TIME_OUT |
505 | HTTP_VERSION_NOT_SUPPORTED |
506 | VARIANT_ALSO_NEGOTIATES |
507 | INSUFFICIENT_STORAGE |
508 | LOOP_DETECTED |
509 | BANDWIDTH_LIMIT_EXCEEDED |
510 | NOT_EXTENDED |
511 | NETWORK_AUTHENTICATION_REQUIRED |
StandardHttpError.js is released under a Lesser GNU Affero General Public License, which in summary means:
For more convoluted language, see the LICENSE
file.
Andri Möll typed this and the code.
Monday Calendar supported the engineering work.
If you find StandardHttpError.js needs improving, please don't hesitate to type to me now at andri@dot.ee or create an issue online.
1.2.0 (Oct 4, 2015)
Restores status code names and constants to pre Node v4 times (Node v0.12) for backwards compatibility. Will release StandardHttpError.js v2 briefly with Node v4's names and constants.
Adds new status codes and constants from Node v4:
Code | Name
------|-----
208
| ALREADY_REPORTED
226
| IM_USED
421
| MISDIRECTED_REQUEST
508
| LOOP_DETECTED
Makes StandardHttpError
inherit from StandardError
so you could more
easily differentiate between bugs (usually thrown as TypeError
,
SyntaxError
et al.) from user-facing errors that you've intentionally
thrown. If all of your custom errors inherit from StandardError
(StandardError.js), this will
come in handy.
var StandardError = require("standard-error")
var HttpError = require("standard-http-error")
function magic(n) {
if (isNaN(n)) throw new TypeError("Bug! Should never be NaN!")
if (n <= 0) throw new HttpError(422, "Think positively!")
// ...
}
try { magic(42) }
catch (ex) {
if (ex instanceof StandardError) console.error("Uh-oh: " + ex.message)
else throw ex
}
Make sure your dependencies have been deduped (see npm dedupe
) to ensure
a single StandardError
instance (needed for instanceof
to work) across
your whole app.
FAQs
Standard HTTP error class. Proper serialization, no bloat. Extensible.
The npm package standard-http-error receives a total of 87,878 weekly downloads. As such, standard-http-error popularity was classified as popular.
We found that standard-http-error demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.