Last active
July 29, 2018 06:19
-
-
Save filippo/8824085 to your computer and use it in GitHub Desktop.
Error management in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* From the article "The Art of Error" | |
* http://dailyjs.com/2014/01/30/exception-error/ | |
*/ | |
/* node example */ | |
var assert = require('assert'); | |
var util = require('util'); | |
function NotFound(message) { | |
Error.call(this); | |
this.message = message; | |
} | |
util.inherits(NotFound, Error); | |
var error = new NotFound('/bitcoin-wallet not found'); | |
assert(error.message); | |
assert(error instanceof NotFound); | |
assert(error instanceof Error); | |
assert.equal(error instanceof RangeError, false); | |
/* in http add status code */ | |
function NotFound(message) { | |
Error.call(this); | |
// this line is for node / chrome. Other environments use different methods | |
Error.captureStackTrace(this, arguments.callee); | |
this.message = message; | |
this.statusCode = 404; | |
} | |
/* than in express use something like this */ | |
app.use(function(err, req, res, next) { | |
console.error(err.stack); | |
if (!err.statusCode || err.statusCode === 500) { | |
emails.error({ err: err, req: req }); | |
} | |
res.send(err.statusCode || 500, err.message); | |
}); | |
/* | |
* In un sistema basato su callback verifico se il primo | |
* argomento della callback (l'errore) è settato e mi comporto di conseguenza. | |
* | |
* if (err) { | |
* return handleError(err); | |
* } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment