Gathering detailed insights and metrics for restify-errors
Gathering detailed insights and metrics for restify-errors
Gathering detailed insights and metrics for restify-errors
Gathering detailed insights and metrics for restify-errors
npm install restify-errors
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
144 Stars
127 Commits
30 Forks
13 Watching
4 Branches
19 Contributors
Updated on 10 Mar 2024
JavaScript (96.05%)
Makefile (3.79%)
Shell (0.16%)
Cumulative downloads
Total Downloads
Last day
-15.9%
45,801
Compared to previous day
Last week
15.9%
266,897
Compared to previous week
Last month
63.7%
1,020,824
Compared to previous month
Last year
-3.3%
7,825,658
Compared to previous year
4
12
1
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:
1const err = new errors.InternalServerError(priorErr, {
2 message: 'boom!',
3 context: { foo: 'bar' }
4});
In 6.x:
1const err = new errors.InternalServerError({
2 cause: priorErr,
3 info: { foo: 'bar' }
4}, '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:
1var errors = require('restify-errors'); 2var nerror = require('@netflix/nerror'); 3 4var err = new errors.InternalServerError({ 5 info: { 6 foo: 'bar' 7 } 8}); 9errors.info(err); // => { foo: 'bar' } 10verror.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:
1var errors = require('restify-errors'); 2 3server.get('/foo', function(req, res, next) { 4 5 if (!req.query.foo) { 6 return next(new errors.BadRequestError()); 7 } 8 9 res.send(200, 'ok!'); 10 return next(); 11});
You can easily do instance checks against the Error objects:
1function redirectIfErr(req, res, next) { 2 var err = req.data.error; 3 if (err) { 4 if (err instanceof errors.InternalServerError) { 5 next(err); 6 } else if (err instanceof errors.NotFoundError) { 7 res.redirect('/NotFound', next); 8 } 9 } 10}
You can also check against the .code
or .name
properties in case there are
multiple copies of restify-error in your application process:
1function redirectIfErr(req, res, next) { 2 var err = req.data.error; 3 if (err) { 4 if (err.name === 'InternalServerError' || 5 err.code === 'InternalServer') { 6 next(err); 7 } else if (err instanceof errors.NotFoundError) { 8 res.redirect('/NotFound', next); 9 } 10 } 11}
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()
:
1function render(req, res, next) { 2 res.send(new errors.InternalServerError()); 3 return next(); 4} 5 6// => restify will render an application/json response with an http 500: 7// { 8// code: 'InternalServerError', 9// message: '' 10// }
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:
1function render(req, res, next) {
2 var myErr = new errors.InvalidVersionError({
3 statusCode: 409
4 }, 'Version not supported with current query params');
5
6 res.send(myErr);
7 return next();
8}
9
10// => even though InvalidVersionError has a built-in status code of 400, it
11// has been customized with a 409 status code. restify will now render an
12// application/json response with an http 409:
13// {
14// code: 'InvalidVersionError',
15// message: 'Version not supported with current query params'
16// }
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:
1function wrapError(req, res, next) {
2
3 if (req.error) {
4 var myErr = new errors.InternalServerError(req.error, 'bad times!');
5 return next(myErr);
6 }
7 return next();
8}
This will allow Error objects to maintain context from previous errors, giving you full visibility into what caused an underlying issue:
1console.log(myErr.message);
2// => 'bad times!'
3
4console.log(myErr.toString());
5// => InternalServerError: bad times!; caused by Error: file lookup failed!
6
7// if you're using Bunyan, you'll get rich stack traces:
8bunyanLogger.info(myErr);
9
10InternalServerError: bad times!
11 at Object.<anonymous> (/Users/restify/test.js:30:16)
12 at Module._compile (module.js:460:26)
13 at Object.Module._extensions..js (module.js:478:10)
14 at Module.load (module.js:355:32)
15 at Function.Module._load (module.js:310:12)
16 at Function.Module.runMain (module.js:501:10)
17 at startup (node.js:129:16)
18 at node.js:814:3
19Caused by: Error: file lookup failed!
20 at Object.<anonymous> (/Users/restify/test.js:29:15)
21 at Module._compile (module.js:460:26)
22 at Object.Module._extensions..js (module.js:478:10)
23 at Module.load (module.js:355:32)
24 at Function.Module._load (module.js:310:12)
25 at Function.Module.runMain (module.js:501:10)
26 at startup (node.js:129:16)
27 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:
1var bunyan = require('bunyan'); 2var restifyErrors = require('restify-errors'); 3 4var log = bunyan.createLogger({ 5 name: 'myLogger', 6 serializers: { 7 err: restifyErrors.bunyanSerializer 8 } 9}); 10 11var err = new restifyErrors.InternalServerError({ 12 info: { 13 foo: 'bar', 14 bar: 1 15 } 16}, 'cannot service this request'); 17 18log.error(err, 'oh noes');
1[2016-08-31T22:27:13.117Z] ERROR: log/51633 on laptop: oh noes (err.code=InternalServer) 2 InternalServerError: cannot service this request! (foo="bar", bar=1) 3 at Object.<anonymous> (/restify/test.js:11:11) 4 at Module._compile (module.js:409:26) 5 at Object.Module._extensions..js (module.js:416:10) 6 at Module.load (module.js:343:32) 7 at Function.Module._load (module.js:300:12) 8 at Function.Module.runMain (module.js:441:10) 9 at startup (node.js:139:18) 10 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:
1var underlyingErr = new Error('boom');
2var multiErr = new verror.MultiError([
3 new Error('boom'),
4 new restifyErrors.InternalServerError({
5 cause: underlyingErr,
6 info: {
7 foo: 'bar',
8 baz: 1
9 }
10 }, 'wrapped')
11]);
12
13log.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:
1var bunyan = require('bunyan'); 2var restifyErrors = require('restify-errors'); 3 4var log = bunyan.createLogger({ 5 name: 'myLogger', 6 serializers: restifyErrors.bunyanSerializer.create({ 7 topLevelFields: true 8 }) 9}); 10 11var err = new Error('pull!'); 12err.espresso = 'normale'; 13 14log.error(err, 'oh noes!');
1[2018-05-22T01:32:25.164Z] ERROR: myLogger/61085 on laptop: oh noes! 2 Error: pull! (espresso="normale") 3 at Object.<anonymous> (/restify/serializer.js:11:11) 4 at Module._compile (module.js:577:32) 5 at Object.Module._extensions..js (module.js:586:10) 6 at Module.load (module.js:494:32) 7 at tryModuleLoad (module.js:453:12) 8 at Function.Module._load (module.js:445:3) 9 at Module.runMain (module.js:611:10) 10 at run (bootstrap_node.js:387:7) 11 at startup (bootstrap_node.js:153:9)
You can also create your own Error subclasses by using the provided
makeConstructor()
method.
1errors.makeConstructor('ExecutionError', {
2 statusCode: 406,
3 failureType: 'motion',
4 message: 'my default message'
5});
6var myErr = new errors.ExecutionError('bad joystick input!');
7
8console.log(myErr instanceof ExecutionError);
9// => true
10
11console.log(myErr.message);
12// => 'ExecutionError: bad joystick input!'
13
14console.log(myErr.failureType);
15// => 'motion'
16
17console.log(myErr.statusCode);
18// => 406
19
20console.log(myErr.stack);
21
22ExecutionError: bad joystick input!
23 at Object.<anonymous> (/Users/restify/test.js:30:16)
24 at Module._compile (module.js:460:26)
25 at Object.Module._extensions..js (module.js:478:10)
26 at Module.load (module.js:355:32)
27 at Function.Module._load (module.js:310:12)
28 at Function.Module.runMain (module.js:501:10)
29 at startup (node.js:129:16)
30 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:
1make githooks
Before committing, run the prepush hook:
1make prepush
If you have style errors, you can auto fix whitespace issues by running:
1make codestyle-fix
Copyright (c) 2018 Alex Liu
Licensed under the MIT license.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 10/27 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More