Ready to take your JavaScript development to the next level? Meet npm Enterprise - the ultimate in enterprise JavaScript. Learn more »

fancy-errors

0.1.2 • Public • Published

fancy-errors

Node.js developer's Swiss Army knife for those damned errors.

fancy-errors

Features

  • Named errors & codes (beauties like ValidationError, FileNotFoundError or HTTPError)
  • Error wrapping that helps you catch 'em all!
  • Utility functions for catching and logging errors
  • Translates .errno like 'ENOENT' into more meaningful message
  • Pretty and colorful error stacks
  • sprintf support (via util.format)
  • Pre-defined common errors
  • and your own custom errors

Install

$ npm install fancy-errors

Basic usage

var errors = require('fancy-errors');
 
// Simple error
throw new errors.Error('Something went %s wrong', 'terribly');
 
// HTTPError, throws err.code = 404, err.message = 'Not found'
throw new errors.HTTPError(404);
 
// Custom error name
throw new errors.NamedError('PaymentGatewayError', 'Error message');

Wrapping

require('fs').stat('/file/nonexistent', function(err, stats){
  if(err){
    throw new error.Error(err, 'Reading stats failed');
  }
});

will produce this output:

Error: Reading stats failed
 ←  Error: ENOENT, stat '/file/nonexistent' (no such file or directory)
 
Stack trace:
 ↳  test.js:36
 ...

You can wrap as many errors as you need:

var err1 = new errors.Error('Low level error');
var err2 = new errors.Error(err1, 'Higher level error');
var err3 = new errors.Error(err2, 'Top level error');
 
console.log(err3.stack);

this will produce something like this:

Error: Top level error
 ←  Error: Higher level error
 ←  Error: Low level error
 ...

Error names

Is there any easier way how to programmatically handle errors then using err.name?

try {
  if(!url){
    throw new error.ArgumentError('Invalid URL');
  }
  throw new errors.HTTPError(500);
  
} catch (err){
  if(err.name === 'HTTPError'){
    res.statusCode = err.code;
    res.end(err.message);
    
  } else if(err.name === 'ArgumentError') {
    res.end(err.message);
  }
}

Error codes

The .code property can be populated directly from the error's message if the message begins with capitalized word followed by a comma.

var err = new errors.Error('INVALID_USERNAME, Username not found');
console.log(err.code); // outputs `INVALID_USERNAME`

Pre-defined errors

  • AuthenticationError(message)
  • ArgumentError(message)
  • ConflictError(message)
  • ConnectionError(message)
  • DirectoryNotFoundError(message)
  • FatalError(message)
  • FileLoadError(message)
  • FileNotFoundError(message)
  • ForbiddenError(message)
  • HTTPError(statusCode, statusMessage)
  • IOError(message)
  • InvalidParameterError(parameterName, message)
  • MissingParameterError(parameterName, message)
  • NotAcceptableError(message)
  • NotAllowedError(message)
  • NotFoundError(message)
  • PreconditionError(message)
  • RangeError(message)
  • RateLimiterError(message)
  • ReferenceError(message)
  • ResourceBusyError(message)
  • TimeoutError(message)
  • TooLargeError(message)
  • TypeError(message)
  • UnsupportedError(message)
  • URIError(message)
  • URITooLongError(message)
  • ValidationError(message)

Define your own

You can also define your own errors using .define helper:

errors.define('MyFancyError', 'This is some fancy default message');
throw new errors.MyFancyError();

this will output:

MyFancyError: This is some fancy default message
...

What the **** is ENOENT?

You should already know what ENOENT means, but still it is nice to have some meaningful error message. When you wrap an error with .errno property, a human-readable string will be appended to the error's message.

Transforms this ugly beast:

Error: ENOENT, stat '/file/nonexistent'

into this beauty:

Error: ENOENT, stat '/file/nonexistent' (no such file or directory)

.catch

This helper makes it easier to handle error passed into the callback.

This example silently ignores any incoming error:

someFunc(function(err, data){
  if(!errors.catch(err)){
    // all good, .catch returns `undefined` if there is no error
  }
});

But if you need to wrap this function and properly call the callback with an error:

function readFile(callback){
  someFunc(function(err, data){
    // .catch will call `callback` with an error if present
    if(!errors.catch(err, callback)){
      callback(undefined, data);
    }
  });
}

.catch does something similar to this:

if(err){
  if(typeof callback === 'function'){
    callback(err);
  }
} else {
  // all good
}

.catchName

Similator to .catch but accepts the name of the error as the first argument and will catch ONLY errors that match the name.

if(!errors.catchName('FatalError', err)){
  // all other errors except FatalError will not be catched
}

.log

This helper is in it's way similar to .catch, but instead of ignoring the error or passing it to the callback, it simple outputs the error to stderr

someFunc(function(err, data){
  if(!errors.log(err)){
    // all good, .log returns `undefined` if there is no error
  }
});

.log does something similar to this:

if(err){
  console.error(err);
} else {
  // all good
}

.fatal

Sometimes it is needed to simply throw an error if it occurs and .fatal will hadle this case for you. It will also wrap the original error with your message.

someFunc(function(err, data){
  errors.fatal(err, 'Reading data failed');
  
  // all good here, .fatal will throw only if there is an error
});

will output:

FatalError: Reading data failed
 ←  Error: ENOENT, stat '/file/nonexistent' (no such file or directory)
 ...

.statusCode(err)

This helper function returns a HTTP status code for the given error.

errors.statusCode(new errors.NotFoundError()); // returns 404

.logLevel(err)

Returns a log level ('fatal', 'warning' or 'debug') for pre-defined errors.

errors.logLevel(new errors.NotFoundError()); // returns 'warning'
errors.logLevel(new errors.FatalError()); // returns 'fatal'
errors.logLevel(new errors.Error()); // returns 'debug'

.serialize()

Returns simple object represenatation of the error usually used for logging or for the server response.

errors.serialize(new errors.NotFoundError('File /file/nonexistent not found'));
 
{
  "error": "File /file/nonexistent not found",
  "errorName": "NotFoundError",
  "errorCode": undefined
}

Pretty stack

Error stack is automaticaly prettified. But this feature is available only in development environment (NODE_ENV). In production, you will get standard stack as you know it.

Test

$ npm test

License

MIT

Keywords

none

install

npm i fancy-errors

Downloadsweekly downloads

82

version

0.1.2

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability