Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including standard-http-error with all npm packages installed. Try it out:

var standardHttpError = require("standard-http-error")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

standard-http-error v2.0.1

Standard HTTP error class. Proper serialization, no bloat. Extensible.

StandardHttpError.js

NPM version Build status

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").

Installing

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).

Using

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:

PropertyValue
name"HttpError"
code404
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.

Creating a new instance by error name

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.

Setting a custom message

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.

Setting custom properties

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.

Subclassing StandardHttpError

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.

Switching based on error codes

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")
}

Using with Express

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.

CodeName
100CONTINUE
101SWITCHING_PROTOCOLS
102PROCESSING
200OK
201CREATED
202ACCEPTED
203NON_AUTHORITATIVE_INFORMATION
204NO_CONTENT
205RESET_CONTENT
206PARTIAL_CONTENT
207MULTI_STATUS
208ALREADY_REPORTED
226IM_USED
300MULTIPLE_CHOICES
301MOVED_PERMANENTLY
302FOUND
303SEE_OTHER
304NOT_MODIFIED
305USE_PROXY
307TEMPORARY_REDIRECT
308PERMANENT_REDIRECT
400BAD_REQUEST
401UNAUTHORIZED
402PAYMENT_REQUIRED
403FORBIDDEN
404NOT_FOUND
405METHOD_NOT_ALLOWED
406NOT_ACCEPTABLE
407PROXY_AUTHENTICATION_REQUIRED
408REQUEST_TIMEOUT
409CONFLICT
410GONE
411LENGTH_REQUIRED
412PRECONDITION_FAILED
413PAYLOAD_TOO_LARGE
414URI_TOO_LONG
415UNSUPPORTED_MEDIA_TYPE
416RANGE_NOT_SATISFIABLE
417EXPECTATION_FAILED
418IM_A_TEAPOT
421MISDIRECTED_REQUEST
422UNPROCESSABLE_ENTITY
423LOCKED
424FAILED_DEPENDENCY
425UNORDERED_COLLECTION
426UPGRADE_REQUIRED
428PRECONDITION_REQUIRED
429TOO_MANY_REQUESTS
431REQUEST_HEADER_FIELDS_TOO_LARGE
500INTERNAL_SERVER_ERROR
501NOT_IMPLEMENTED
502BAD_GATEWAY
503SERVICE_UNAVAILABLE
504GATEWAY_TIMEOUT
505HTTP_VERSION_NOT_SUPPORTED
506VARIANT_ALSO_NEGOTIATES
507INSUFFICIENT_STORAGE
508LOOP_DETECTED
509BANDWIDTH_LIMIT_EXCEEDED
510NOT_EXTENDED
511NETWORK_AUTHENTICATION_REQUIRED

License

StandardHttpError.js is released under a Lesser GNU Affero General Public License, which in summary means:

  • You can use this program for no cost.
  • You can use this program for both personal and commercial reasons.
  • You do not have to share your own program's code which uses this program.
  • You have to share modifications (e.g. bug-fixes) you've made to this program.

For more convoluted language, see the LICENSE file.

About

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.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free