I have inherited a codebase which contains code such as the following (note: example code is PHP):
try {
// Do something which doesn't intentionally throw exceptions.
} catch (\Exception $e) {
$this->log->log($e->getMessage());
$this->product->setError($e->getMessage());
return false;
}
So essentially, the code is catching the exception. Logging it, and the failing silently (apart from the log message).
This behaviour seems to make sense in production, but makes development much more difficult (as stack traces have to be looked up in log files, rather than being printed to the console). So I have come up with the following function:
private function tryCatch ($func) {
// Bind closure, so that $this allows it to access class properties
if (is_object($func) && ($func instanceof Closure)) {
\Closure::bind($func, $this, "static");
}
if (\App::environment('test')) {
return $func();
} else {
try {
return $func();
} catch (\Exception $e) {
$this->log->log($e->getMessage());
$this->product->setError($e->getMessage());
return false;
}
}
}
which can then be used like so:
$this->tryCatch(function () {
// Do something
});
This code special-cases the 'test' environment which it calls the passed in function without exception handling (so any exceptions remain unhandled). In every other environment (e.g. production), it wraps the passed in closure in a try-catch block in production behaves as the code originally behaved.
This solutions solves my problems, but it seems a bit hacky, and leaves me with aI have nagging feeling that it isn't a good idea.
My question: Is there any reason why I shouldn't do this? Or is there a better way of handling this situation?