|
| 1 | +## How to Implement and Use Your Own Exception Converters |
| 2 | + |
| 3 | +Implementing and using custom exception converters can make exception handling in your application more structured and versatile. With the `ProblemDetailsSymfonyBundle`, it is possible to extend and customize the way exceptions are converted to `ProblemDetails` responses. Here is how you can create and use your own exception converters: |
| 4 | + |
| 5 | +### Steps to Implement a Custom Exception Converter |
| 6 | +1. **Understand the Exception Conversion** |
| 7 | + - Exception converters are responsible for transforming an exception into a structured `ProblemDetails` response adhering to RFC 9457. |
| 8 | + - The `ProblemDetailsFactory` can be used to create such responses within the converter. |
| 9 | +2. **Create Your Custom Exception Converter** |
| 10 | + - Create a class that handles the logic for converting specific exception types or scenarios into `ProblemDetails`. |
| 11 | + |
| 12 | +```php |
| 13 | + namespace App\ExceptionConverter; |
| 14 | + |
| 15 | + use Psr\Log\LoggerInterface; |
| 16 | + use Phauthentic\ProblemDetails\ExceptionConverterInterface; |
| 17 | + use Phauthentic\ProblemDetails\ProblemDetailsFactoryInterface; |
| 18 | + use Symfony\Component\HttpFoundation\Response; |
| 19 | + |
| 20 | + class CustomExceptionConverter implements ExceptionConverterInterface |
| 21 | + { |
| 22 | + public function __construct( |
| 23 | + private ProblemDetailsFactoryInterface $problemDetailsFactory, |
| 24 | + private LoggerInterface $logger |
| 25 | + ) { |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Converts the given exception to a ProblemDetails instance. |
| 30 | + */ |
| 31 | + public function convert(\Throwable $exception): Response |
| 32 | + { |
| 33 | + // Example exception check |
| 34 | + if ($exception instanceof \DomainException) { |
| 35 | + $this->logger->error('Domain Exception occurred: '.$exception->getMessage()); |
| 36 | + |
| 37 | + return $this->problemDetailsFactory->createResponse( |
| 38 | + type: 'https://example.net/domain-error', |
| 39 | + detail: $exception->getMessage(), |
| 40 | + status: 400, |
| 41 | + title: 'Domain Error' |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + // Default: throw the exception further if it cannot be converted |
| 46 | + throw $exception; |
| 47 | + } |
| 48 | + } |
| 49 | +``` |
| 50 | + |
| 51 | +3. **Register the Exception Converter in Your Application** |
| 52 | + - Register your custom exception converter as a service in Symfony, and ensure it integrates into the exception handling workflow. |
| 53 | + |
| 54 | +```yaml |
| 55 | + # config/services.yaml |
| 56 | + services: |
| 57 | + App\ExceptionConverter\CustomExceptionConverter: |
| 58 | + arguments: |
| 59 | + $problemDetailsFactory: '@Phauthentic\ProblemDetails\ProblemDetailsFactoryInterface' |
| 60 | + $logger: '@logger' |
| 61 | +``` |
0 commit comments