I've looked through the threads here on this subject and can't find what I want.
I have a bunch of functions that return string and I want them to not return a string if the input is bad and I don't want the program to exit开发者_如何学编程 either AND I don't want to wrap every call in try / catch.
function foo(num){
if(num > 5){
throw SomeException("Input too big")
}else{
return "bar"+num
}
}
I want to log an error like "6 is too big for foo", instead of exiting the program. But this will be kind of an api, so I don't want the user to have to try/catch every time they use one of these functions. This is a nodejs script.
this works, but is a awkward:
f = {
command : function(cmd,arg){
try {
console.log(q[cmd](arg));
}
catch (e) {
console.log("Error: " + e + " for " + cmd);
}
},
foo : function(str){
throw ("foo error");
},
foo2 : function(str){
throw ("foo2 error");
}
};
f.command("foo",2);
f.command("foo2",3);
[[Edit]] It's a nodeJS script. Then make the API asynchronous. We do not do synchronous operations in nodeJS. Please conserve the event loop.
You can also rework your API to be asynchronous
function foo(num, cb){
if(num > 5){
cb(SomeException("Input too big"));
}else{
cb(null, "bar"+num);
}
}
foo(5, function(err, data) {
...
});
You can reference a public logger instance.
MyLibrary.errorHandler = defaultErrorHandler() || config.errorHandler
Then have the defaultErrorHandler be
function(error) {
if (console && console.log) { console.log(error.message); }
$("#errordiv").text(error.message);
}
function foo(num){
if(num > 5){
MyLibrary.errorHandler(new Exception("blargh"));
}else{
return "bar"+num;
}
}
If you're creating an API that others will use, and you want to signal that an error happened, well... throw an exception. If that exception doesn't get caught by the programmer using your API, that's their fault, not yours; on the other hand, if their code goes all wonky because your function does something really weird on an error, well... okay, that's still the other programmer's fault for not properly checking input coming into your API, but be a good citizen and help out their debugging by throwing that exception. They may dislike you for putting exceptions everywhere, but they'll hate you if your code just silently does really weird stuff instead of providing a good indication of what the error is.
I'd say log the error, too, but you're doing this in JavaScript, where there isn't any such facility.
And for the record, this is coming from a programmer who has used APIs that both do and do not throw exceptions on errors; the ones that do throw them are generally the ones I consider to be better-written.
精彩评论