Define an array of errors in JavaScript based on a specification.
Easily be able to detect types of error messages by defining an error specification,
and then using instanceof
and/or code
to determine the type of error and handle
errors appropriately.
Extending 'Error' is not trivial as lineNumber
, columnNumber
and fileName
in addition to stack
properties are vendor specific. For example within Mozilla Firefox, the lineNumber
property will reference the incorrect line, and will point to a line inside of the class rather then where the error was thrown. Currently lineNumber
, columnNumber
and fileName
are not accessible from Firefox. Please see Error - JavaScript | MDN for more information.
// detect the error type with instanceof
if (e instanceof Errors.InvalidY) {
...
}
// detect the error type with error code
if (e.code === 500) {
...
}
Works in both web browsers and in Node.js
<script type="text/javascript" src="dist/erray.min.js"></script>
<script>
var Erray = window.erray;
</script>
npm install erray --save
var Erray = require('erray');
Errors are defined with a concise specification.
var Errors = Erray([
'InvalidX', // basic usage, only specify a name
{
name: 'InvalidY', // specify the name
message: 'Invalid Y value for this function', // set a default static message
code: 500 // add an optional code
},
{
name: 'InvalidXY',
message: function(x, y) { // specify a function to handle arguments
return 'Invalid values x: ' + x + ' and y: ' + y + ' for input.';
}
},
{
name: 'NotFound',
code: 404
}
]);
Errors can then be thrown or returned by instantiating a new error:
var error = new Errors.NotFound('The requested information is not found');
Error messages can be generated by passing a function in the specification that will handle arguments when the error is instantiated.
var x = 10;
var y = 23;
var error = new Errors.InvalidXY(x,y);
throw error;
// Example Log
//
// InvalidXY: Invalid values x: 10 and y: 23 for input.
// at repl:1:7
// at REPLServer.self.eval (repl.js:110:21)
// at repl.js:249:20
// at REPLServer.self.eval (repl.js:122:7)
// at Interface.<anonymous> (repl.js:239:12)
// at Interface.EventEmitter.emit (events.js:95:17)
// at Interface._onLine (readline.js:202:10)
// at Interface._line (readline.js:531:8)
// at Interface._ttyWrite (readline.js:760:14)
// at ReadStream.onkeypress (readline.js:99:10)
The specification can also include a default message, or send it directly when instantiating.
// use the default message
var error = new Errors.InvalidY();
// or you can supply a message directly
var error = new Errors.InvalidY('The value of y: "' + y + '" is invalid.');