Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
restify-errors
Advanced tools
The restify-errors package provides a set of HTTP and REST error classes for use with the Restify framework. It simplifies error handling by providing a consistent way to create and manage errors in your Restify applications.
Creating Standard HTTP Errors
This feature allows you to create standard HTTP errors like 404 Not Found, 500 Internal Server Error, etc. The code sample demonstrates creating a 404 Not Found error.
const restifyErrors = require('restify-errors');
const error = new restifyErrors.NotFoundError('Resource not found');
console.log(error);
Custom Error Classes
You can create custom error classes that extend the base HttpError class. The code sample shows how to create a custom error with a 418 status code.
const restifyErrors = require('restify-errors');
class CustomError extends restifyErrors.HttpError {
constructor(message) {
super({ statusCode: 418, message });
this.name = 'CustomError';
}
}
const error = new CustomError('I am a teapot');
console.log(error);
Error Serialization
Errors can be serialized to JSON for easy transmission over HTTP. The code sample demonstrates serializing an InternalServerError to JSON.
const restifyErrors = require('restify-errors');
const error = new restifyErrors.InternalServerError('Something went wrong');
const serializedError = JSON.stringify(error.toJSON());
console.log(serializedError);
The http-errors package provides a set of HTTP error classes for use with any Node.js framework. It is similar to restify-errors but is more generic and can be used with Express, Koa, and other frameworks.
The boom package is a set of utilities for creating HTTP errors for use with Hapi.js. It provides a similar set of features to restify-errors but is designed to work seamlessly with the Hapi.js framework.
The create-error package allows you to create custom error classes with ease. It is more lightweight compared to restify-errors and can be used in any Node.js application.
A collection of HTTP and REST Error constructors.
This module ships with a set of constructors that can be used to new up Error objects with default status codes.
The module ships with the following HttpErrors:
and the following RestErrors:
Some of the status codes overlap, since applications can choose the most applicable error type and status code for a given scenario. Should your given scenario require something more customized, the Error objects can be customized with an options object.
Install the module with: npm install restify-errors
For TypeScript type definitions: npm install @types/restify-errors
As of 6.x this module is now a thin wrapper over the VError module. Every Error constructor exposed by this module inherits from VError, which means the constructor signatures are now also identical to VError.
All VError static methods are also re-exported on the restify-errors export object. For all intents and purposes, you should treat this library as an extension of VError, with a list of built in constructors and sugar functions.
The primary difference between the old 5.x and 6.x API is a reshuffling of the option names and where they are provided. In 5.x:
const err = new errors.InternalServerError(priorErr, {
message: 'boom!',
context: { foo: 'bar' }
});
In 6.x:
const err = new errors.InternalServerError({
cause: priorErr,
info: { foo: 'bar' }
}, 'boom!');
In 5.x, the .context
property was used to store and capture context about the
scenario causing the error. This concept is still supported, but now uses
VError's info object to achieve the same thing. As it uses the VError APIs, all
you have to now is pass info
instead of context
when creating an Error.
For migration purposes, accessing the info object via .context
will be
supported through 6.x, and the serializer will also continue to support it.
Both may be deprecated in future versions. To access the info object, you can
use the VError static method .info()
, which is re-exported on the
restify-errors exports:
var errors = require('restify-errors');
var nerror = require('@netflix/nerror');
var err = new errors.InternalServerError({
info: {
foo: 'bar'
}
});
errors.info(err); // => { foo: 'bar' }
verror.info(err); // => { foo: 'bar' }
Note that using verror directly also works, since all Error objects created by this library inherit from VError.
In 5.x, using the makeConstructor
class would add the constructor itself to
restify-error's module.exports object. This was problematic in complex
applications, where custom Error constructors could be shared across multiple
modules in multiple contexts.
As a result, in 6.x, custom constructors are no longer stored on the module.exports object, and it is the user's responsibility to retain a reference to those custom constructors.
In your application, create errors by using the constructors:
var errors = require('restify-errors');
server.get('/foo', function(req, res, next) {
if (!req.query.foo) {
return next(new errors.BadRequestError());
}
res.send(200, 'ok!');
return next();
});
You can easily do instance checks against the Error objects:
function redirectIfErr(req, res, next) {
var err = req.data.error;
if (err) {
if (err instanceof errors.InternalServerError) {
next(err);
} else if (err instanceof errors.NotFoundError) {
res.redirect('/NotFound', next);
}
}
}
You can also check against the .code
or .name
properties in case there are
multiple copies of restify-error in your application process:
function redirectIfErr(req, res, next) {
var err = req.data.error;
if (err) {
if (err.name === 'InternalServerError' ||
err.code === 'InternalServer') {
next(err);
} else if (err instanceof errors.NotFoundError) {
res.redirect('/NotFound', next);
}
}
}
All Error objects in this module ship with both a toString()
and toJSON()
methods. Restify uses these methods to "render" errors when they are passed to
res.send()
:
function render(req, res, next) {
res.send(new errors.InternalServerError());
return next();
}
// => restify will render an application/json response with an http 500:
// {
// code: 'InternalServerError',
// message: ''
// }
You can override either of these methods to customize the serialization of an error.
If you'd like to change the status code or message of a built-in Error, you can pass an options object to the constructor:
function render(req, res, next) {
var myErr = new errors.InvalidVersionError({
statusCode: 409
}, 'Version not supported with current query params');
res.send(myErr);
return next();
}
// => even though InvalidVersionError has a built-in status code of 400, it
// has been customized with a 409 status code. restify will now render an
// application/json response with an http 409:
// {
// code: 'InvalidVersionError',
// message: 'Version not supported with current query params'
// }
Like WError, all constructors accept an Error object as the first argument to build rich Error objects and stack traces. Assume a previous file lookup failed and an error was passed on:
function wrapError(req, res, next) {
if (req.error) {
var myErr = new errors.InternalServerError(req.error, 'bad times!');
return next(myErr);
}
return next();
}
This will allow Error objects to maintain context from previous errors, giving you full visibility into what caused an underlying issue:
console.log(myErr.message);
// => 'bad times!'
console.log(myErr.toString());
// => InternalServerError: bad times!; caused by Error: file lookup failed!
// if you're using Bunyan, you'll get rich stack traces:
bunyanLogger.info(myErr);
InternalServerError: bad times!
at Object.<anonymous> (/Users/restify/test.js:30:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Caused by: Error: file lookup failed!
at Object.<anonymous> (/Users/restify/test.js:29:15)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Since errors created via restify-errors inherit from VError, you'll get out of
the box support via bunyan's standard serializers. If you are using the
info
property, you can use the serializer shipped with restify-errors:
var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');
var log = bunyan.createLogger({
name: 'myLogger',
serializers: {
err: restifyErrors.bunyanSerializer
}
});
var err = new restifyErrors.InternalServerError({
info: {
foo: 'bar',
bar: 1
}
}, 'cannot service this request');
log.error(err, 'oh noes');
[2016-08-31T22:27:13.117Z] ERROR: log/51633 on laptop: oh noes (err.code=InternalServer)
InternalServerError: cannot service this request! (foo="bar", bar=1)
at Object.<anonymous> (/restify/test.js:11:11)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
You can, of course, combine this with the standard set of serializers that bunyan ships with. VError's MultiError is also supported:
var underlyingErr = new Error('boom');
var multiErr = new verror.MultiError([
new Error('boom'),
new restifyErrors.InternalServerError({
cause: underlyingErr,
info: {
foo: 'bar',
baz: 1
}
}, 'wrapped')
]);
log.error(multiErr, 'oh noes');
[2016-08-31T22:48:43.244Z] ERROR: logger/55311 on laptop: oh noes
MultiError 1 of 2: Error: boom
at Object.<anonymous> (/restify/test.js:16:5)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
MultiError 2 of 2: InternalServerError: wrapped (foo="bar", baz=1)
at Object.<anonymous> (/restify/test.js:17:5)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
Caused by: Error: boom
at Object.<anonymous> (/restify/test.js:14:21)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
For more information about building rich errors, check out VError.
The serializer can also be customized. The serializer currently supports the following options:
options.topLevelFields
{Boolean} - if true, serializes all top level fields
found on the error object, minus "known" Error/VError fields. This can be
useful if errors are created in dependencies that don't use VError or
restify-errors to maintain context in an independent object.For example:
var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');
var log = bunyan.createLogger({
name: 'myLogger',
serializers: restifyErrors.bunyanSerializer.create({
topLevelFields: true
})
});
var err = new Error('pull!');
err.espresso = 'normale';
log.error(err, 'oh noes!');
[2018-05-22T01:32:25.164Z] ERROR: myLogger/61085 on laptop: oh noes!
Error: pull! (espresso="normale")
at Object.<anonymous> (/restify/serializer.js:11:11)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.runMain (module.js:611:10)
at run (bootstrap_node.js:387:7)
at startup (bootstrap_node.js:153:9)
You can also create your own Error subclasses by using the provided
makeConstructor()
method.
errors.makeConstructor('ExecutionError', {
statusCode: 406,
failureType: 'motion',
message: 'my default message'
});
var myErr = new errors.ExecutionError('bad joystick input!');
console.log(myErr instanceof ExecutionError);
// => true
console.log(myErr.message);
// => 'ExecutionError: bad joystick input!'
console.log(myErr.failureType);
// => 'motion'
console.log(myErr.statusCode);
// => 406
console.log(myErr.stack);
ExecutionError: bad joystick input!
at Object.<anonymous> (/Users/restify/test.js:30:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
All Error constructors are variadic and accept the following signatures, which are identical to the VError and WError signatures.
restify-errors adds additional options for the final signature:
options.restCode
{Number} - a description code for your Error. This is used
by restify to render an error when it is directly passed to res.send()
. By
default, it is the name of your error constructor (e.g., the restCode for a
BadDigestError is BadDigest).options.statusCode
{Number} - an http status codeoptions.toJSON
{Function} - override the default toJSON()
methodoptions.toString
{Function} - override the default toString()
methodCreates a custom Error constructor, adds it to the existing exports object.
name
{String} - the name of your Errordefaults
{Object} - an object of default values that will added to the
prototype. It is possible to override the default values for restCode
,
statusCode
, toString()
and toJSON()
.Returns: {Constructor}
Create an Error object using an http status code. This uses http
module's
STATUS_CODES
to do the status code lookup. Thus, this convenience method
is useful only for creating HttpErrors, and not RestErrors.
statusCode
{Number} - an http status codeargs
- arguments to be passed on to the constructorReturns: {Object} an Error object
Add unit tests for any new or changed functionality. Ensure that lint and style checks pass.
To start contributing, install the git pre-push hooks:
make githooks
Before committing, run the prepush hook:
make prepush
If you have style errors, you can auto fix whitespace issues by running:
make codestyle-fix
Copyright (c) 2018 Alex Liu
Licensed under the MIT license.
8.0.2 (2019-12-13)
<a name="8.0.1"></a>
FAQs
Collection of Error objects shared across restify components.
The npm package restify-errors receives a total of 211,117 weekly downloads. As such, restify-errors popularity was classified as popular.
We found that restify-errors demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 7 open source maintainers 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.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.