Does anybody know a good strategy for handling exceptions and errors. At the moment I have different pieces of code handling their own validation/errors/exception but I would really have a centralized strategy. I was thinking of some global notification system that passes some errors/exceptions to the user like validation. Other errors I would post to my back-end and log them.
For example a validation error could contain th开发者_JS百科e element that caused the error. That way I can add a class to highlight it and append some text before or after.
So if anybody has some concrete examples on how to do this I would really appreciate it.
If it's worth it, you could customize errors and build a function around these which contains default behaviour:
function errorHandler() {
var error = arguments[1] ; //!! pass the error
/* additional arguments */
var errorCode = error.message ;
var errorMap = { //!! a map that matches error codes to default behaviour
"customErrorName":function() {
/* default behaviour for this kind of error */
} ,
/* more custom error codes and default behaviour */
}
if(errorCode in errorMap) { //!! error code has a default behaviour
errorMap[ errorCode ]() ; //!! call default behaviour
} else {
/* log unknown error */
}
}
You would implement this in a try { ... } catch(e) { ... }
block:
try {
/* your code */
if(someErrorCondition) {
throw new Error("someError") ;
}
} catch(e) {
errorHandler(e) ;
}
There are default error types in javascript too. There's a list in the following link: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error
If your main problem is about validation I think the most concrete way to go about it would be to use the jQuery validation plug-in which is truely customizable and has a good base for your to start handling exceptions.
I am not a big fan of try catch blocks in javascript but I think also you can start from giving particular codes for your self to different errors and handle them in switch case blocks.
精彩评论