Can't catch exceptions in laravel - php

I have the following situation:
try {
DB::beginTransaction();
$task = new Task();
$task->setTracker("");
//thrown \Symfony\Component\Debug\Exception\FatalThrowableError
DB::commit();
}catch (\Exception $e){
DB::rollBack();
Log::error($e);
//throw $e;
}
I am not entering to the catch area.
Any idea why?
update
This is the error thrown:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to App\Models\Task::setTracker() must be an instance of Carbon\Carbon, integer given, called in /var/www/app/Services/ShareLogic.php on line 60
and will not be catched
Thanks

Catching Throwable did the trick.
Have no idea why?
Anyone does?

It does not catch the exception because you are trying to catch \Exception which Symfony\Component\Debug\Exception\FatalThrowableError does not extend.
Instead try to catch the actual exception by importing it..
use Symfony\Component\Debug\Exception\FatalThrowableError;
And then you can do..
try {
//
} catch(FatalThrowableError e) {
//
}
Edit
Ok, so in addition to the above solution it seems PHP 7+ handles error a bit differently than PHP 5. So try this..
try {
//
} catch(Error $e) {
// This should work
} catch(Throwable $e) {
// This should work as well
}

Symfony's Debug component is much more sophisticated in order to log and report all kinds of errors but take look at this simple example (php 7.1.x):
<?php
class MyUncatchableError extends Exception {}
function myExceptionHandler($e) {
throw new MyUncatchableError('BANG: '.$e->getMessage());
}
set_exception_handler('myExceptionHandler');
$foo = true;
try {
$foo->modify();
} catch (Exception $e) {
echo 'nope';
} catch (MyUncatchableError $e) {
echo 'nope2';
}
What will be the outcome? Well:
Fatal error: Uncaught MyUncatchableError: BANG: Call to a member function modify() on boolean in /in/WJErU:6
Stack trace:
0 [internal function]: myExceptionHandler(Object(Error))
1 {main}
thrown in /in/WJErU on line 6
and you can't catch that exception because you should catch the original.. throwable here, which is Error for this kind of "error". You can catch it by catching "Error" class. And with PHP7 hierarchy it implements Throwable interface, that's why you can't catch it using Exception (because while Exception implements Throwable, Error is no an Exception - see: http://php.net/manual/en/language.errors.php7.php).
And this is true for PHP7+ because with 5.* there was no Throwable nor Error, and doing $foo->modify(); would just stop the script and return a Fatal Error. You can make your own error handler (set_error_handler) and throw an exception there (and Debug component does that for php 5.*) but this method does not work for Fatal Errors. Instead Debug component hooks into script shutdown and reads last error and throws FatalErrorException.
This description may not be completely accurate as I have't dug deeply into Symfony but you can get the idea here.

Related

Laravel exception not catching

I'm trying to do a very basic exception try catch, but it doesn't catch.
$id =0;
try {
$question = $this->model->find($id); // will not find anything since $id = 0
$question->delete(); // throw an exception
return true;
} catch (\Exception $e) {
dd ('hello'); // should end up here, but no?!?!?
} catch (FatalThrowableError $f) {
echo ("fatal"); // or here... but no.
}
but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.
I have tried
use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;
or simply
Exception;
FatalThrowableError;
Also, having the \Exception $e or Exception $e (with or without ) doesn't change anything.
Note that if I add a line like $foo = 4/0 I get into the Exception section (dd (hello)).
in .env APP_DEBUG=true, APP_LOG_LEVEL=debug
I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.
http://php.net/manual/en/language.errors.php7.php
As the Error hierarchy does not inherit from Exception, code that uses
catch (Exception $e) { ... } blocks to handle uncaught exceptions in
PHP 5 will find that these Errors are not caught by these blocks.
Either a catch (Error $e) { ... } block or a set_exception_handler()
handler is required.
You can, additionally, catch (\Throwable $e) {} to account for both Error and Exception types.

Why this Exception can not be handled by catch try method

When i initiate a class which does not exist , It throws the error, I Don't want to halted by that error . So i try trycatch method , But it still giving me same error, Can someone explain why this error is not been catched
I tried
try{$obj = new classname();}
catch(Exception $e){ echo 'class does not exist, move on' ;}
Fatal error: Class 'classname' not found in C:\WampDeveloper\Websites\localhost\webroot\index.php on line 4
Can someone explain why this error can not be catched ?
Is their is another way to catch and handle this kind of errors ?
UPDATE
We can catch mysql fatal errors by try catch method , So don't say fatal errors can not be handeled by try catch method
Two ways to solve this, use a autoloader that runs a custom written function for each object that does not exist so you can try to "include" a file on demand.
function autoload($objname){
if(is_readable(($f = '/path/to/class/'.$objname.'.php'))){
include $f;
} else {
throw Exception("$f does not exist");
}
}
spl_autoload_register('autoload');
new classname(); // try to load /path/to/class/classname.php
Or you can upgrade to PHP 7 where the error logic has had little overhaul:
Hierarchy
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
So a code like this would work:
try{
$obj = new classname();
} catch(Error $er){
echo 'class does not exist, move on';
} catch(Exception $ex){
echo 'a custom exception has been thrown:' . $ex->getMessage();
} catch(Throwable $t){
// Obsolete code, as Throwables are either Error or Exception, that were caught above.
}

Testing PHP parse errors with phpunit

I need to test how our error logger works in various scenarios. One such scenario are parse errors. Here's an example:
public function testParseErrorLogsAnError()
{
$this->assertCount(0, $this->log_handler->getRecords());
try {
eval('<?php not good');
$this->fail('Code above should throw a parse error');
} catch (\Exception $e) {
$this->assertInstanceOf(\ParseError::class, $e);
}
$this->assertCount(1, $this->log_handler->getRecords());
}
Problem is that phpunit always exists with an exception, and never enters catch block. How to disable or orverride phpunit's exception handler, so we can test our own?
For this answer, I'm assuming you're using PHP 7. In PHP 5, Parse Errors cannot be caught and will always terminate your PHP process.
In PHP 7, you can catch Parse Errors using a try/catch statement (contrary to what the other answer says). However, PHP 7's ParseError class extends the Error class, not Exception (see also the documentation). So catch (\Exception $e) will not work, but any of these should:
catch (\ParseError $e) { ...
catch (\Error $e) { ...
catch (\Throwable $e) { ...
Alternatively, use the #expectedException annotation als already suggested by #DevDonkey:
/**
* #expectedException ParseError
*/
public function testParseErrorLogsAnError()
{
eval('<?php not good');
}

PHP Custom Error Handler: How to determine if exception was generated within try{}catch{} block?

I have a custom error handlers:
set_error_handler('API_Error_Handler');
register_shutdown_function('Fatal_Error_Handler'); // This one calls API_Error_Handler eventually
In the following example, both catch{} section AND API_Error_Handler are executed.
try{
// Exception raised here
} catch(Exception $e){
// No error reporting needed, do something else
}
I want ONLY catch{} to execute. How do I do that? Maybe determine within API_Error_Handler whether exception is already caught by try-catch? Or are there other approaches available?
Example code:
set_error_handler(function() {
echo "Error is handled by custom error handler. <br>";
});
try{
new SoapClient('http://bad.address/wsdl');
} catch(Exception $e){
echo "Error is caught. <br>";
}
I think the best way will be to create an Exception class by your self that extends Exception:
class MyCustomException extends \Exception {}
and throw this where you need it. Then change
} catch (Exception $e)
to
} catch (MyCustomException $e)
and you should only get your custom exception catched

Exception handling in PHP: where does $e goes?

I been searching for this and I just seem to run into the same articles, in this code:
try
{
//some code
}
catch(Exception $e){
throw $e;
}
Where does $e gets stored or how the webmaster see it? Should I look for a special function?
An Exception object (in this case, $e) thrown from inside a catch{} block will be caught by the next highest try{} catch{} block.
Here's a silly example:
try {
try {
throw new Exception("This is thrown from the inner exception handler.");
}catch(Exception $e) {
throw $e;
}
}catch(Exception $e) {
die("I'm the outer exception handler (" . $e->getMessage() . ")<br />");
}
The output of the above is
I'm the outer exception handler (This is thrown from the inner exception handler.)
One nice thing is that Exception implements __toString() and outputs a call stack trace.
So sometimes in low-level Exceptions that I know I'm gonna want to see how I got to, in the catch() I simply do
error_log($e);
$e is an instance of Exception or any other class that extended from Exception. Those objects have some specific attributes and methods in common (inherited from the Exception class) you can use. See the chapter about exceptions and the Exception member list for more details.
I'm assuming your using some sort of third party code/library with this code in it that is throwing the exception into your code. You simply have to be ready for an exception to be thrown to catch it, then you can log it/display it however you want.
try {
$Library->procedure();
catch(Exception $e) {
echo $e->getMessage(); //would echo the exception message.
}
For more information read the PHP manual's entry on Exceptions.
The lines:
catch(Exception $e){
throw $e;
}
Don\t make sense. When you catch an Exception you're suppose to do something with the exception like:
catch(Exception $e){
error_log($e->getMessage());
die('An error has occurred');
}
But in your case the Exception is thrown directly to an outer try-block which would already happen.
If you change your code to:
//some code
Would create the exact same behaviour.

Categories