Reputation: 4869
If I have a function which is not declared and resulted in a 500 error and this function is called within the try block, will the insertions done before the function be rolled back?
When I tried the following code, the 500 error is not handled by the catch.
DB::connection()->getPdo()->beginTransaction();
try
{
$helper = new Helper;
$helper->functionThatIsNotDeclared();
DB::connection()->getPdo()->commit();
}
catch( \Exception $e)
{
DB::connection()->getPdo()->rollBack();
}
Is there anyway to handle the 500 error properly?
Thanks in advnace.
Upvotes: 0
Views: 416
Reputation: 8019
Fatal errors in PHP terminate the current code "stack" and jump directly to the shutdown handler, so they avoid try/catch blocks. You could register a fatal error handler:
App::fatal(function() { DB::getPdo()->rollback(); });
But this would likely not work well if there was no transaction started when another fatal error occurs.
The general advice here is to just avoid fatal errors as a whole. Fatal errors indicate a bug in your code as opposed to exceptions which are more "expected" errors happening in your applications.
Upvotes: 1
Reputation: 3879
You can check whether a method exists in PHP by using method_exists()
- http://www.php.net/manual/en/function.method-exists.php
Your code would look something like this:
DB::connection()->getPdo()->beginTransaction();
try
{
$helper = new Helper;
if(method_exists($helper, 'functionThatIsNotDeclared')) {
// The method exists, do something
} else {
// The method doesn't exist, do something else
}
DB::connection()->getPdo()->commit();
}
catch(Exception $e)
{
DB::connection()->getPdo()->rollBack();
}
Though I think the reason why you were getting an error is because of your catch()
- I believe you meant to type catch(Exception $e)
rather than catch( \Exception $e)
.
Upvotes: 2