|
| 1 | +# Error Handling |
| 2 | + |
| 3 | +API Platform Core allows to customize the HTTP status code sent to the clients when exceptions are thrown. |
| 4 | + |
| 5 | +```yaml |
| 6 | +# app/config/config.yml |
| 7 | + |
| 8 | + services: |
| 9 | +# Map exceptions to HTTP status codes using the `exception_to_status` configuration key |
| 10 | + exception_to_status: |
| 11 | + # The 2 following exceptions are handled by default |
| 12 | + Symfony\Component\Serializer\Exception\ExceptionInterface: 400 # Use a raw status code (recommended) |
| 13 | + ApiPlatform\Core\Exception\InvalidArgumentException: 'HTTP_BAD_REQUEST' # Or with a constant of `Symfony\Component\HttpFoundation\Response` |
| 14 | + |
| 15 | + AppBundle\Exception\ProductNotFoundException: 404 # Custom exceptions can easily be handled |
| 16 | +``` |
| 17 | +
|
| 18 | +As in any php application, your exceptions have to extends the \Exception class or any of it's children. |
| 19 | +
|
| 20 | +```php |
| 21 | +<?php |
| 22 | + |
| 23 | +// src/AppBundle/Exception/ProductNotFoundException.php |
| 24 | + |
| 25 | +namespace AppBundle\Exception; |
| 26 | + |
| 27 | +final class ProductNotFoundException extends \Exception |
| 28 | +{ |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +```php |
| 33 | +<?php |
| 34 | + |
| 35 | +// src/AppBundle/Manager/CartManager.php |
| 36 | + |
| 37 | +namespace AppBundle\Manager; |
| 38 | + |
| 39 | +use AppBundle\Entity\Product; |
| 40 | +use AppBundle\Exception\ProductNotFoundException; |
| 41 | + |
| 42 | +final class CartManager |
| 43 | +{ |
| 44 | + private const DOESNOTEXISTS = 51; |
| 45 | + private const DEACTIVATED = 52; |
| 46 | + private const OUTOFSTOCK = 53; |
| 47 | + |
| 48 | + /** |
| 49 | + * @param int $id |
| 50 | + * |
| 51 | + * @throws ProductNotFoundException |
| 52 | + */ |
| 53 | + public function addProductToCart(int $id) |
| 54 | + { |
| 55 | + $product = /*...*/; |
| 56 | + |
| 57 | + if (!$product->getVirtualStock()) { |
| 58 | + // Using internal codes for a better understanding of what's going on |
| 59 | + throw new ProductNotFoundException(self::NOTFOUND_OUTOFSTOCK); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +The exception doesn't have to be a Symfony's `HttpException`. Any type of `Exception` can be thrown. The best part is that API Platform already takes care of how the error is handled and returned. For instance the API is configured to respond in JSON-LD, the error will be returned in this format as well. |
| 66 | + |
| 67 | +Previous chapter: [Pagination](pagination.md) |
| 68 | + |
| 69 | +Next chapter: [The Event System](events.md) |
0 commit comments