
Security News
ECMAScript 2025 Finalized with Iterator Helpers, Set Methods, RegExp.escape, and More
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
common-errors
Advanced tools
Common error classes and utility functions
Applicable when a resource is already in use, for example unique key constraints like a username.
new ArgumentNullError(entityName, arg1, [arg2, arg3, arg4, ...])
Arguments
entityName
- the entity that owns the protected resourceargs
- the fields or attributes that are already in use// Example
throw new errors.ArgumentNull('user', 'username');
### ArgumentError
Applicable when there's a generic problem with an argument received by a function call.
new ArgumentError(argumentName)
Arguments
argumentName
- the name of the argument that has a problem// Example
throw new errors.Argument('username');
### ArgumentNullError
Applicable when an argument received by a function call is null/undefined or empty.
new ArgumentNullError(argumentName)
Arguments
argumentName
- the name of the argument that is null// Example
throw new errors.ArgumentNull('username');
### AuthenticationRequiredError
Applicable when an operation requires authentication
new AuthenticationRequiredError(message)
Arguments
message
- any message// Example
throw new errors.AuthenticationRequiredError("Please provide authentication.")
### GenericError
Applicable for any error returned by a callback, or any time you want to throw a new error that is based from another error.
Call stacks from both errors will be concatenated for a full call stack. This effectively patches a design issue in JavaScript
where logging an error from an asynchronous callback will show only the call stack from the error's context, but does not
show the the stack where it was consumed.
For example, if you perform a SQL query that returns an error with the callback, you don't know where in your code
the offending
query was generated. Wrapping the returned error in your own GenericError will solve this problem.
new GenericError(message[, innerError])
Arguments
message
- any message you wantinnerError
- any error that you want to preserve with the new error// Example
mysql.query('SELECT * `FROM` users', function(err, results){
if(err) return new errors.Generic("Had trouble retrieving users.", err);
console.log(results);
})
### HttpStatusError
Represents a message and a HTTP status code.
new HttpStatusError(status_code[, message])
Arguments
status_code
- any HTTP status code integermessage
- any message// Example
throw new errors.HttpStatus("Not Found", 404);
new HttpStatusError(err[, req])
Figure out a proper status code and message from a given error.
To change the mappings, modify HttpStatusError.message_map
and HttpStatusError.code_map
Arguments
err
- any Error subclassreq
- the request object// Example
throw new errors.HttpStatus("Not Found", 404);
### NotPermittedError
Applicable when an operation is not permitted
new NotPermittedError(message)
Arguments
message
- any message// Example
throw new errors.NotPermitted("username cannot be changed once set.")
### NotSupportedError
Applicable when a certain condition is not supported by your application.
new NotSupportedError(message)
Arguments
message
- a message// Example
throw new errors.NotSupported('Zero values');
### ValidationError
Useful for denoting a problem with a user-defined value. Generally, you wont throw this error.
new ValidationError(message[, code])
Arguments
message
- any messagecode
- an optional error code// Example
function validateUsername(username){
var errors = [];
if(username.length < 3) errors.push(new errors.Validation("username must be at least two characters long", "VAL_MIN_USERNAME_LENGTH"));
if(/-%$*&!/.test(username)) errors.push(new errors.Validation("username may not contain special characters", "VAL_USERNAME_SPECIALCHARS"));
return errors;
}
Modifies an error's stack to include the current stack and logs it to stderr. Useful for logging errors received by a callback.
log(err[, message])
Arguments
err
- any error or error message received from a callbackmessage
- any message you'd like to prepend// Example
mysql.query('SELECT * `FROM` users', function(err, results){
if(err) return errors.log(err, "Had trouble retrieving users.");
console.log(results);
});
### generateClass
Simple interface for generating a new Error class type.
helpers.generateClass(name[, options])
Arguments
name
- The full name of the new Error classoptions
subclass
- The base class for the new Error class. Default is Error
.args
- Array of names of values to accept and store from the class constructor. Default is ['message']
.generateMessage
- A function for defining a custom error message.// Example
var ArgumentNullError = helpers.generateClass("ArgumentNullError", {
subclass: ArgumentError,
args: ['argumentName'],
generateMessage: function(){
return "Missing argument: " + this.argumentName;
}
});
throw new ArgumentNullError("username");
Express middleware for preventing the web server from crashing when an error is thrown from an asynchronous context.
Any error that would have caused a crash is logged to stderr.
// Example
var app = express();
app.use(express.static(__dirname + '/../public'));
app.use(express.bodyParser());
app.use(errors.middleware.crashProtector());
//insert new middleware here
app.get('/healthcheck', function (req, res, next){res.send('YESOK')});
app.use(app.router);
app.use(errors.middleware.errorHandler);
module.exports = app;
### Error Handler
Express middleware that translates common errors into HTTP status codes and messages.
// Example
var app = express();
app.use(express.static(__dirname + '/../public'));
app.use(express.bodyParser());
app.use(errors.middleware.crashProtector());
//insert new middleware here
app.get('/healthcheck', function (req, res, next){res.send('YESOK')});
app.use(app.router);
app.use(errors.middleware.errorHandler);
module.exports = app;
This library was developed by David Fenster at Shutterstock
Copyright (C) 2013-2014 by Shutterstock Images, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Common error classes and utility functions
The npm package common-errors receives a total of 4,465 weekly downloads. As such, common-errors popularity was classified as popular.
We found that common-errors demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 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.
Security News
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
Security News
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.
Research
North Korean threat actors linked to the Contagious Interview campaign return with 35 new malicious npm packages using a stealthy multi-stage malware loader.