Programmers seem divided on how to get asynchronously notified about an error.
Some programmers prefer to use a callback with two arguments: a value and a boolean which tells whether the value isn't erroneous. This has the benefit in that it looks like a try catch
statement:
asyncFunct(function (value, noError) {
if (noError) {
// success, do something with value
} else {
// value is the error which is thrown
}
});
Others prefer the negative (i.e. the boolean should tell whether the value is erroneous). Their reasoning is that if you know that the asynchronous function will never throw an error then you can safely omit the second parameter as follows:
asyncFunction(function (value, isErroneous) {
if (!isErrorneous) {
// success, do something with value
} else {
// value is the error which is thrown
}
});
asyncFunction(function (value) {
// success, do something with value
});
Then there are people who propose separate callbacks for successful execution of asynchronous functions and errbacks for erroneous execution of asynchronous functions. This allows the programmer to select if he want to handle callbacks, errbacks, both or none:
asyncFunction(function (value) {
// success, do something with value
}, function (error) {
// handle the error
});
asyncFunction(function (value) {
// success, do something with value
});
asyncFunction(null, function (error) {
// handle the error
});
I'm not asking for which method you prefer. I'm simply asking for the advantages and disadvantages of each method so that I know which one to use when.
Design Decision:
This is just design decisions, nothing more. If it's standalone parameter, you can have standalone function and create "more beautiful" code (for someone - for someone it's more messy - it's really subjective).
Error complexity:
In some applications you can have more complex errors (filesystem.fileRead
can have FILE_DONT_EXISTS, FILE_LOCKED, NOT_PERMISSIONS..) and in some apps you need just throw error (db.checkConnection
or db.openConnection
).
Order and differences:
Very nice sample for great API is from Amazon, you can check it. http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html
RESPONSE: On asynch function like copyObject(params = {}, callback)
you have callback function, which have always 2 parameters: err (Error)
and data (Object)
in function(err, data) { ... }
. Error is designed like a first parameter because if you have error, you don't have a data. So it's really about priority and about order.
// request
getObject({
param1 : something,
param2 : something,
param3 : something
}, callback);
// response
function callback(error, response){
if error throw err;
// now deal with responsei
}
As you can see, you have both mixed two ways. In request you pass object and function and in response you get error and object (to that request function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With