In our team we often discuss the usage of exceptions inside a function VS some kind of return arrays, but I'm still not sure how to do it the right way. So let's try to ask the question from scratch:
When to use an exception VS returning an array, containing all information about the result?
Example #1
function doAwesomeStuff($foo) {
// prepare return values...
$result = [
'success' => true,
'infoMessage' => '',
'stuffDetails' => []
];
// check params...
if (!is_numeric($foo)) {
$result['success'] = false;
$result['infoMessage'] = 'Something went wrong...';
return $result;
}
// do something else...
if ($somethingElseWentWrong) {
$result['success'] = false;
$result['infoMessage'] = 'Something else went wrong...';
return $result;
}
// add new data...
$result['stuffDetails'] = [
'foo' => 'bar'
];
// done...
return $result;
}
$foo = 42;
$awesomeStuff = doAwesomeStuff($foo);
if ($awesomeStuff['success'] === false) {
echo $awesomeStuff['infoMessage'];
// some error handling stuff...
}
// do some other awesome stuff
// ...
Example 2
function doAwesomeStuff($foo) {
// prepare return value...
$stuffDetails = [];
// check params...
if (!is_numeric($foo)) {
throw new InvalidArgumentException('Something went wrong...');
}
// do something else...
if ($somethingElseWentWrong) {
throw new AnotherException('Something else went wrong...');
}
// add new data...
$stuffDetails = [
'foo' => 'bar'
];
// done...
return $stuffDetails;
}
try {
$foo = 42;
$awesomeStuff = doAwesomeStuff($foo);
// do some other awesome stuff...
// ...without caring about error handling at this point (it's all done in catch blocks)
} catch InvalidArgumentException($e) {
echo $e->getMessage();
// some error handling stuff...
} catch AnotherException($e) {
echo $e->getMessage();
// some error handling stuff...
}
So which version is the "better" way of error handling, #1 or #2? Is it just a matter of taste or are there real arguments for one of the two versions?
There is one simple best practice "rule" for methods or functions which tells you to have single exit points in functions. Is this already the answer, which means it would be v2?
I'd really appreciate all thoughts about this topic :-)