As a PHP developer, you may use exceptions, because they allow you to notice when something has gone wrong or the user has acted in an unusual way (such as division by zero). Without exceptions, your application would end up presenting unwanted errors and being much more difficult to debug. It is also important that you halt execution immediately and take another course of action.
Exceptions are really simple, and they will make your development progress easier. When you learn how to use exceptions, this will be a usual part of your development.
What Is an Exception?
I think the best definition for exceptions is given by Martin Fowler:
Exceptions signal something outside the expected bounds of behavior of the code in question.
Exactly, in fact, an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When you throw
(create an exception object and hand it to the runtime system) an exception, the system will catch
it by searching for the appropriate handler and returning the proper message.
try { // the code goes here } catch (Exception $e) { // if an exception happened in the try block above }
When Do We Need to Use Exceptions?
Use exceptions when your system is faced with exceptional circumstances that prevent the system from taking over. We use exceptions only when the system is not able to determine what has happened. Martin Fowler believes that “if a failure is expected behavior, then you shouldn’t be using exceptions”. This means you should use exceptions where you are not able to determine the error. Exceptions should only be used in exceptional circumstances.
Note: Exceptions are not good for handling logic operations.
For a system like validating input, using exceptions is wrong. First of all, the input text will be determined, and in an application like this we should report a collection of errors instead of a single error. I believe in eliminating the use of exceptions in any circumstance where we might expect validation failures.
Catching an exception is very important, because if you do not catch an exception the system will return an error. The catching operation must be as close to the point of failure as possible.
What Are Laravel Exceptions?
Laravel uses exception Handler, which is a class in App\Exceptions\Handler.php
. This class contains two main methods (the renderHttpException
method, which is used for all HTTP Exceptions, like 404s and 503s, is in the parent class of Handler). The first one is report
, which is used to log exceptions or send them to an external service. Here’s an example of the report method:
public function report(Exception $e) { if ($e instanceof CustomException) { // } return parent::report($e); }
The second one is render
. The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. Here’s an example of the render method:
public function render($request, Exception $e) { if ($e instanceof CustomException) { return response()->view('errors.custom', [], 500); } return parent::render($request, $e); }
Note: You can use the $dontReport
property of the exception handler to ignore exceptions by type.
You can override Laravel exception methods in your own exception like so:
public function render($request, Exception $e) { if (config('app.debug')) { return parent::render($request, $e); } return $this->handle($request, $e); }
This will render when config debug is true.
How to Create Your Own Laravel Exception?
You may need to create your own exception class. You need to extend from the Laravel base Exception class—I’ve created an abstract class that will behave as the base class of our custom Exception class. Create a file in App/Exceptions/monException.php
:
namespace App\Exceptions; use Exception; abstract class monException extends Exception { protected $id; protected $details; public function __construct($message) { parent::__construct($message); } protected function create(array $args) { $this->id = array_shift($args); $error = $this->errors($this->id); $this->details = vsprintf($error['context'], $args); return $this->details; } private function errors($id) { $data= [ 'not_found' => [ 'context' => 'The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.', ] // ... ]; return $data[$id]; } }
And your Exception class:
namespace App\Exceptions; class NotFoundmonException extends monException { public function __construct() { $message = $this->create(func_get_args()); parent::__construct($message); } }
You can use the above class in your code:
try { throw new \App\Exceptions\NotFoundmonException('not_found'); } catch(\App\Exceptions\NotFoundmonException $e) { return $e->getMessage(); }
Beside the Laravel core Exception class, you can use the Assertion package. This can be used as a third-party exception class; you may use this to skip spaghetti if
blocks in your code.
To install the Assertion package, you should run the following command:
composer require beberlei/assert
For example, if you want to check the email address of a user, you may do this:
use Assert\Assertion; use Assert\AssertionFailedException; //... try { Assertion::email($value, "The value must be valid E-mail address"); } catch(AssertionFailedException $e) { $e->getValue(); // the value that caused the failure $e->getConstraints(); // the additional constraints of the assertion. }
Conclusion
Regardless of the language that you choose to use, exceptions are very important to understand as they help us to control the execution of the flow of an application.
Furthermore, they helps us to log problems when they occur and help to make our application more robust.
As you can see from the work covered in this tutorial, Laravel is a framework that offers great exception handling functionality web building web applications.
Comments