• Stars
    star
    284
  • Rank 140,281 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Common error classes and utility functions

common-errors

Common error classes and utility functions

  • Full suite of node.js Error classes like most other modern languages
  • Append stack traces from other asynchronously generated Errors
  • Generate your own custom Error classes in one line
  • Map HTTP status codes to Errors for automatic handling in web services and applications

Build Status

Install

npm install common-errors

Class Directory

Common Error Classes

Utility Functions

Express Middleware Functions

Common Error Classes

AlreadyInUseError

Applicable when a resource is already in use, for example unique key constraints like a username.

new AlreadyInUseError(entityName, arg1, [arg2, arg3, arg4, ...])

Arguments

  • entityName - the entity that owns the protected resource
  • args - the fields or attributes that are already in use
// Example
throw new errors.AlreadyInUseError('user', 'username');

ArgumentError

Applicable when there's a generic problem with an argument received by a function call.

new ArgumentError(argumentName[, inner_error])

Arguments

  • argumentName - the name of the argument that has a problem
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.ArgumentError('username', err);

ArgumentNullError

Applicable when an argument received by a function call is null/undefined or empty.

new ArgumentNullError(argumentName[, inner_error])

Arguments

  • argumentName - the name of the argument that is null
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.ArgumentNullError('username', err);

AuthenticationRequiredError

Applicable when an operation requires authentication

new AuthenticationRequiredError(message, [inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.AuthenticationRequiredError("Please provide authentication.", err)

ConnectionError

Applicable when an error occurs on a connection.

new ConnectionError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.ConnectionError('database connection no longer available', err);

DataError

Applicable when an error occurs on or with an external data source.

new DataError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.DataError('Too many rows returned from database', err);

MemcachedError

Applicable when an error occurs while using memcached.

new MemcachedError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.MemcachedError('Expected value not found', err);

MongoDBError

Applicable when an error occurs while using MongoDB.

new MongoDBError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.MongoDBError('Retrieved value not in expected format', err);

RedisError

Applicable when an error occurs while using redis.

new RedisError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.RedisError('expected value not found in redis', err);

RollbackError

Applicable when a transaction was unexpectedly rolled back.

new RollbackError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.RollbackError('database transaction was unexpectedly rolled back', err);

SQLError

Applicable when an error occurs while using a SQL database.

new SQLError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.SQLError('foreign key constraint violated', err);

TransactionError

Applicable when an error unexpectedly interrupts a transaction.

new TransactionError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.data.TransactionError('transaction already complete', err);

Error

This is roughly the same as the native Error class. It additionally supports an inner_error attribute.

new Error(message, [inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.Error("Please provide authentication.", err)

HttpStatusError

Represents a message and a HTTP status code.

new HttpStatusError(status_code[, message])

Arguments

  • status_code - any HTTP status code integer
  • message - any message
// Example
throw new errors.HttpStatusError(404, "Not Found");
new HttpStatusError(err[, req])

Figure out a proper status code and message from a given error. The current mapping of error codes to HTTP status codes is as follows:

{
    "ValidationError": 400,
    "ArgumentError": 400,
    "AuthenticationRequiredError": 401,
    "NotPermittedError": 403,
    "ArgumentNullError": 404 // , or 400 depending on what's wrong with the request
    "NotFoundError": 404,
    "NotSupportedError": 405,
    "AlreadyInUseError": 409,
}

To change the mappings, modify HttpStatusError.message_map and HttpStatusError.code_map

Arguments

  • err - any instanceof Error
  • req - the request object
// Example
throw new errors.HttpStatusError(err, req);

InvalidOperationError

Applicable when an invalid operation occurs.

new InvalidOperationError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.InvalidOperationError('divide by zero', err);

IOError

Base class for Errors while accessing information using streams, files and directories.

new IOError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.IOError("Could not open file", err)

DirectoryNotFoundError

Applicable when part of a file or directory cannot be found.

new DirectoryNotFoundError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.DirectoryNotFoundError("/var/log", err)

DriveNotFoundError

Applicable when trying to access a drive or share that is not available.

new DriveNotFoundError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.DriveNotFoundError("c", err)

EndOfStreamError

Applicable when reading is attempted past the end of a stream.

new EndOfStreamError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.EndOfStreamError("EOS while reading header", err)

FileLoadError

Applicable when a file is found and read but cannot be loaded.

new FileLoadError(message[, inner_error])

Arguments

  • file_name - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.FileLoadError("./package.json", err)

FileNotFoundError

Applicable when an attempt to access a file that does not exist on disk fails.

new FileNotFoundError(message[, inner_error])

Arguments

  • file_name - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.io.FileNotFoundError("./package.json", err)

SocketError

Applicable when an error occurs on a socket.

new SocketError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.SocketError('socket no longer available', err);

NotFoundError

Applicable when an attempt to retrieve data yielded no result.

new NotFoundError(entity_name[, inner_error])

Arguments

  • entity_name - a description for what was not found
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.NotFoundError("User", err)

NotImplementedError

Applicable when a requested method or operation is not implemented.

new NotImplementedError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.NotImplementedError("Method is not yet implemented.", err)

NotPermittedError

Applicable when an operation is not permitted

new NotPermittedError(message[, inner_error])

Arguments

  • message - any message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.NotPermittedError("username cannot be changed once set.", err)

NotSupportedError

Applicable when a certain condition is not supported by your application.

new NotSupportedError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.NotSupportedError('Zero values', err);

OutOfMemoryError

Applicable when there is not enough memory to continue the execution of a program.

new OutOfMemoryError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.OutOfMemoryError('Maximum mem size exceeded.', err);

RangeError

Represents an error that occurs when a numeric variable or parameter is outside of its valid range. This is roughly the same as the native RangeError class. It additionally supports an inner_error attribute.

new RangeError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.RangeError("Value must be between " + MIN + " and " + MAX, err);

ReferenceError

Represents an error when a non-existent variable is referenced. This is roughly the same as the native ReferenceError class. It additionally supports an inner_error attribute.

new ReferenceError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.ReferenceError("x is not defined", err);

StackOverflowError

Applicable when the execution stack overflows because it contains too many nested method calls.

new StackOverflowError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.StackOverflowError('Stack overflow detected.', err);

SyntaxError

Represents an error when trying to interpret syntactically invalid code. This is roughly the same as the native SyntaxError class. It additionally supports an inner_error attribute.

new SyntaxError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.SyntaxError("Unexpected token a", err);

TimeoutError

Applicable when an operation takes longer than the alloted amount.

new TimeoutError(time[, inner_error])

Arguments

  • time - a time duration
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.TimeoutError('100ms', err);

TypeError

Represents an error when a value is not of the expected type. This is roughly the same as the native TypeError class. It additionally supports an inner_error attribute.

new TypeError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.TypeError("number is not a function", err);

URIError

Represents an error when a value is not of the expected type. This is roughly the same as the native URIError class. It additionally supports an inner_error attribute.

new URIError(message[, inner_error])

Arguments

  • message - a message
  • inner_error - the Error instance that caused the current error. Stack trace will be appended.
// Example
throw new errors.URIError("URI malformed", err);

ValidationError

Useful for denoting a problem with a user-defined value. Generally, you won't throw this error. It serializes to JSON, and it can also function as an envelope for multiple errors.

new ValidationError(message, [code], [field])

Arguments

  • message - any message
  • code - an optional error code
  • field - an optional description of the data

Methods

  • addError(error) - add an error object to the errors array, and return this.
  • addErrors(errors) - append an array of error objects to the errors array, and return this.
// Example
function validateUsername(username){
	var errors = new errors.ValidationError();
	if(username.length < 3) errors.addError(new errors.ValidationError("username must be at least two characters long", "VAL_MIN_USERNAME_LENGTH", "username"));
	if(/-%$*&!/.test(username)) errors.addError(new errors.ValidationError("username may not contain special characters", "VAL_USERNAME_SPECIALCHARS", "username"));
	return errors;
}

Utility Functions

Log

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 callback
  • message - 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);
});

prependCurrentStack

Modifies an error's stack to include the current stack without logging it. Useful for logging errors received by a callback.

prependCurrentStack(err)

Arguments

  • err - any error or error message received from a callback
// Example
mysql.query('SELECT * `FROM` users', function(err, results){
	if(err) {
		return errors.prependCurrentStack(err); // caller has better idea of source of err
	}
	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 class
  • options
    • extends - The base class for the new Error class. Default is Error.
    • globalize - Boolean (default true) to store the Error in global space so that the Error is equivalent to others included from other versions of the module.
    • args - Array of names of values to accept and store from the class constructor. Default is ['message', 'inner_error'].
    • generateMessage - A function for defining a custom error message.
// Example
var ArgumentNullError = helpers.generateClass("ArgumentNullError", {
  extends: ArgumentError,
  args: ['argumentName'],
  generateMessage: function(){
    return "Missing argument: " + this.argumentName;
  }
});

throw new ArgumentNullError("username");

Express Middleware Functions

Crash Protector

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;

Authors

This library was developed by David Fenster at Shutterstock

Contribute

Please do! Check out our Contributing guidelines.

License

MIT © 2013-2017 Shutterstock Images, LLC

More Repositories

1

rickshaw

JavaScript toolkit for creating interactive real-time graphs
JavaScript
6,540
star
2

lil-brother

Track clicks and other client-side events on web pages
JavaScript
223
star
3

changeDPI

Javascript library that allows you to change an image's DPI settings in the browser
JavaScript
203
star
4

ntf

Network Testing Framework
JavaScript
98
star
5

basecoat

A small, fast, static free micro framework that makes no assumptions and requires no conventions. It is well suited for migrating off legacy code, building services, or complex websites.
PHP
42
star
6

shutterstock-heatmap-toolkit

Shutterstock's interactive heatmap toolkit powered by heatmap.js and Solr
JavaScript
36
star
7

api-clients-examples

Shutterstock API Clients and Examples
32
star
8

armrest

A high-level HTTP / REST client for Node
JavaScript
29
star
9

gremlin-aws-sigv4

Extension for Apache's TinkerPop3 Gremlin JS driver compatible with IAM Database Authentication for Neptune
JavaScript
29
star
10

fnFlow

Pronounced "effin' flow" because it's so badass, fnFlow is a Javascript control flow library heavily influenced by Caolan McMahon's async that encourages a proper functional design pattern.
JavaScript
21
star
11

postcss-copy-assets

PostCSS plugin to copy assets referenced by relative url()s into a build directory.
JavaScript
18
star
12

opentree

Generate an Org Chart from Workday
Java
18
star
13

public-api-javascript-sdk

Simplify and speed up integration by using a JavaScript library to access our API.
JavaScript
17
star
14

node-procedural-async

Write procedural style code that runs asynchronously. It may look synchronous, but it's not!
JavaScript
17
star
15

UrlManager

Javascript class for getting and setting url parameters
JavaScript
15
star
16

tungsten-replicator

Shutterstock git mirror of Tungsten Replicator.
Java
14
star
17

juxtaposer

Screen shot capture and comparison tool for testing website changes.
JavaScript
14
star
18

kafkajs-async-retry

Provides a KafkaJS-compatible handler for processing messages that facilitates publishing to delayed-retry or dead-letter topics
TypeScript
12
star
19

ntfserver

Network Testing Framework Server
JavaScript
11
star
20

terraform-aws-s3-squid-proxy-farm

AWS Terraform module to create an S3 Squid proxy farm on AWS
HCL
10
star
21

task

Task-based git release management
Perl
10
star
22

node-shutterstock-api

⛔️ DEPRECATED - A client for the Shutterstock API written in Node
JavaScript
9
star
23

presto

PHP REST Orchestration
PHP
8
star
24

ruby-shutterstock-api

⛔️ DEPRECATED - Ruby client for Shutterstock public API
Ruby
7
star
25

node-favicon-video

Videos in your favicon!
JavaScript
7
star
26

php-shutterstock-api

PHP Client to interact with the Shutterstock API
PHP
7
star
27

orc-metadata-reader

Python ORC metadata reader
C
7
star
28

Data-Partial-Google

Filter data structures for "partial responses," Google style
Perl
6
star
29

welcome

Welcome to the Shutterstock Community
6
star
30

shutterstock-cli

A command-line utility that allows you to interact with the Shutterstock public API.
Python
5
star
31

oplog

An operations log
JavaScript
5
star
32

devent-router

Route Devent messages by topic
C
5
star
33

node-timing-middleware

Expose request timing in express apps
JavaScript
5
star
34

SVC

MVC for javascript with the observer pattern
JavaScript
5
star
35

public-api-sdk-generator

Mustache
4
star
36

shutterstock-oauth-sample

⛔️ DEPRECATED - Shutterstock Oauth Sample code, for interacting with the Shutterstock API
JavaScript
4
star
37

devent-forwarder

Forward Devent messages via HTTP, UDP or ZMQ
JavaScript
4
star
38

spark-phrases

phrase detection using Google's Word2phrase
Scala
4
star
39

php-shutterstock-api-example

Example PHP application that interfaces with Shutterstock API
PHP
3
star
40

node-icu-numformat

Node.JS bindings to libicu number formatting functions
C++
3
star
41

MogileFS-Plugin-Migrate

MogileFS plugin for moving files across domains
Perl
3
star
42

astore

Shared request aggregator and temp entity store
JavaScript
3
star
43

gitbook-plugin-related-links

Gitbook plugin that collects and shows related links
JavaScript
3
star
44

go-stockutil

A collection of various useful utility functions for Golang applications
Go
3
star
45

wordpress-plugin

PHP
2
star
46

Stemming-Exceptions

A collection of stemming exceptions for different languages.
2
star
47

perl-moosex-role-rest-consumer

Perl
2
star
48

Net-Statsd-Client

Perl
2
star
49

newrelic-console-logging

Forwards all logs emitted through console.log (and friends) to New Relic's application logging aggregation endpoint.
JavaScript
2
star
50

a-swig-service

A service that well, serves html from swig templates
JavaScript
2
star
51

ntfd

Network Testing Framework Daemon
JavaScript
2
star
52

Webdam-Wordpress-Asset-Chooser

Webdam Wordpress Asset Chooser Plugin
PHP
2
star
53

bigstock-php-client

⛔️ DEPRECATED - PHP Client for the Bigstock API
PHP
2
star
54

api-php-client

⛔️ DEPRECATED - Sample PHP client implementation of Shutterstock API
PHP
2
star
55

bigstock-ruby-client

⛔️ DEPRECATED - A Ruby client for Bigstock's API
Ruby
1
star
56

bristlecone

A set of test tools that perform useful services for measuring database and database cluster performance
Java
1
star
57

perl-devent-client

Perl client for writing Devent messages
Perl
1
star
58

homebrew-shutterstock

Homebrew tap for Shutterstock
Ruby
1
star
59

shutterstock-ui-wizard

HTML
1
star
60

shutterstock-js-cli

Shutterstock in your /usr/bin
JavaScript
1
star
61

http-close-channel

Express middleware for managing and closing HTTP channels
JavaScript
1
star
62

mold

JavaScript
1
star
63

node-debug-middleware

Log all middleware that is slow to respond
JavaScript
1
star
64

perl-webservice-swigclient

A fast client for swig.io
Perl
1
star
65

p-map-iterable

Performs a concurrent mapping with back pressure (won't iterate all source items if the consumer is not reading).
TypeScript
1
star
66

Tree-SEMETrie

Single-Edge-Multi-Edge Trie
Perl
1
star
67

perl-db-transaction

feather-weight transaction management for your DBI handles
Perl
1
star
68

vertica-cli

Command-line Vertica client in Node.js
JavaScript
1
star
69

WebService-Shutterstock

⛔️ DEPRECATED - Easy access to Shutterstock's public API
Perl
1
star
70

bigstock-node-client

⛔️ DEPRECATED - A node.js client to use with Bigstock, an easy-to-use marketplace for stock images.
JavaScript
1
star