tounaf / exception-handler
Exception handler for symfony project
Installs: 44
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 2
Open Issues: 0
Type:package
Requires
- symfony/error-handler: ^7.1 || 6.4.* || 5.4.* || 4.4.*
- symfony/http-foundation: 6.4.* || 6.3.* || 6.2.* || 6.1.* || 5.4.* || 4.4.*
Requires (Dev)
- enlightn/security-checker: ^1.11
- friendsofphp/php-cs-fixer: ^3.39
- rector/rector: *
- squizlabs/php_codesniffer: *
- symfony/test-pack: ^1.1
- symfony/var-dumper: ^6.4 || ^6.3 || ^6.2
This package is auto-updated.
Last update: 2024-11-19 14:44:21 UTC
README
Create handler class for each exception that you throw in your application.
1 - Installation
composer require tounaf/exception-handler
2 - Features
this package allows to separate the handler class by exception to avoid code coupling : - One classe handler is responsible for exception - Render response throught different output (html, json, xml) - Decorate classe handler for other needs (Write to log file, send exception to mail, to sentry)
3 - Create Exception Handler class
Create an class and implement the ExceptionHandlerInteface interface. It contains two methods:
** handleException: This method have Throwble as argument and returns a Symfony Response
** supportsException: This method have Throwble as argument and return boolean.
Example:
First create Exception to handle through the app.
<?php namespace App\Handler\Exception; class MyException extends \Exception { }
Then create the handler that handle this exception
<?php namespace App\Handler\Exception; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; use Tounaf\Exception\ExceptionHandlerInterface; class MyExceptionHandler implements ExceptionHandlerInterface { // return an JsonResponse public function handleException(\Throwable $throwable): Response { // your logic return new JsonResponse(['message' => $throwable->getMessage(), 'code' => 12]); } // public function supportsException(\Throwable $throwable): Response { return $throwable instanceof MyException; } }
When MyException is thrown, the MyExceptionHandler class is called by the system . For example:
namespace App\Service; use App\Handler\Exception\MyException; class MyService { public function someFunction() { // your logic throw new MyException(); } }