In addition to Laravel/PHP Exceptions, you may also encounter PHP Errors for syntax issues or invalid things:
Or:
What if you want to handle these errors more gracefully? Well, you can manage them as Exceptions!
There are a few different things that can cause PHP Errors:
auth()->user()
, but you accidentally type auth()->user
- this will cause an error because you're trying to call a property that does not exist.file_get_content($filename);
instead of file_get_contents($filename);
.file_get_contents($filename, $context, $offset);
instead of file_get_contents($filename);
.User::create($request)
instead of User::create($request->all())
.10 / 0
.These all cause PHP Errors because they are invalid things to do in PHP. Yet, they will only produce an error if they are executed. So, if you have a typo in your code that is never executed, you will never see the error.
PHP Errors are different from Exceptions in a few ways:
In short, getting an Exception means that you have something malformed within the logic of your application. Getting a PHP Error means that you have something wrong with the syntax of your application. And that's significantly worse!
Once you learn about Exceptions and how to handle them with a Try-Catch block - you may want to do the same to prevent PHP errors:
try { $this->importData();} catch (\Exception $e) { dd("General Exception: " . $e->getMessage());}
But this doesn't work as you would expect:
A php Error is not an Exception, so this block will not catch it. Instead, it would be best if you caught it like this:
try { $this->importData();} catch (\Exception $e) { dd("General Exception: " . $e->getMessage());} catch (\Error $e) { dd("General error: " . $e->getMessage());}
That way, you can catch the PHP Error just like an Exception:
It even works for a variety of PHP Errors:
try { functionThatDoesntExistYet();} catch (\Exception $e) { dd("General Exception: " . $e->getMessage());} catch (\Error $e) { dd("General error: " . $e->getMessage());}
You can even catch a specific PHP Error:
public function __invoke() { // ... try { $this->importData(); // <-- We forgot to add $row as a parameter here } catch (\Exception $e) { dd("General exception: " . $e->getMessage()); } catch (\ArgumentCountError $e) { dd("Argument count error:" . $e->getMessage()); } catch (\Error $e) { dd("General error: " . $e->getMessage()); }} public function importData($row){ // ...}
Running this, we'll see that we caught the specific PHP Error:
You can do this for all the errors in the documentation.
Notice: We only recommend you do this in your application if you understand the implications. It is just an example of how to avoid breaking your application when you encounter a PHP Error.