atournayre / exception-handler
Centralized exception handling with Symfony and custom PHP attributes
Installs: 2 482
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: >=8.1
- symfony/event-dispatcher: ^5.4 || ^6.0
- symfony/http-foundation: ^5.4 || ^6.0
- symfony/http-kernel: ^5.4 || ^6.0
- symfony/routing: ^5.4 || ^6.0
This package is auto-updated.
Last update: 2023-12-02 10:04:44 UTC
README
This component helps handle exceptions inside Symfony.
It is inspired from the article Centralized exception handling with Symfony and custom PHP attributes by Dejan Angelov. Read it before!
Install
Composer
composer require atournayre/exception-handler
Usage
- Define
HttpStatusCodeExceptionHandler
as a listener in your application. - Declare attributes on your existing/new exceptions classes.
- Remove (or do not catch exception) in your controller.
- It works!
Define HttpStatusCodeExceptionHandler
as a listener in your application
# config/services.yaml services: Atournayre\Component\ExceptionHandler\Handler\HttpStatusCodeExceptionHandler: tags: - { name: kernel.event_listener, event: kernel.exception }
Declare attributes on your existing/new exceptions classes.
// Example for a NotFound (404) #[NotFound] class OrderNotFound extends Exception { public function __construct(OrderId $id) { parent::__construct( sprintf('The order "%s" could not be found.', (string) $id) ); } }
// Example for a UnprocessableEntity (422) #[UnprocessableEntity] class OrderAlreadyShipped extends Exception { ... }
// Example for a Forbidden (403) #[Forbidden] class CustomerMismatch extends Exception { ... }
Contributing
Of course, open source is fueled by everyone's ability to give just a little bit of their time for the greater good. If you'd like to see a feature or add some of your own happy words, awesome! Tou can request it - but creating a pull request is an even better way to get things done.
Either way, please feel comfortable submitting issues or pull requests: all contributions and questions are warmly appreciated :).