You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public function checkProductAvailability(GetResponseForControllerResultEvent $event)
61
+
{
62
+
$product = $event->getControllerResult();
63
+
$method = $event->getRequest()->getMethod();
64
+
65
+
if (!$product instanceof Product || Request::METHOD_GET !== $method) {
66
+
return;
67
+
}
68
+
69
+
if (!$product->getVirtualStock()) {
70
+
// Using internal codes for a better understanding of what's going on
71
+
throw new ProductNotFoundException(self::OUTOFSTOCK);
72
+
}
73
+
}
74
+
}
75
+
```
76
+
77
+
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, if the API is configured to respond in JSON-LD, the error will be returned in this format as well.
78
+
79
+
```json
80
+
{
81
+
"@context": "/contexts/Error",
82
+
"@type": "Error",
83
+
"hydra:title": "An error occurred",
84
+
"hydra:description": "53"
85
+
}
86
+
```
87
+
88
+
Is what you get, with an HTTP status code 404 as defined in the configuration.
89
+
90
+
## Validation errors
91
+
92
+
API Platform does handle the validation errors responses for you. You can define a Symfony supported constraint, or a custom constraint upon any `ApiResource` or it's properties.
93
+
94
+
```php
95
+
<?php
96
+
97
+
// src/AppBundle/Entity/Product.php
98
+
99
+
namespace AppBundle\Entity;
100
+
101
+
use ApiPlatform\Core\Annotation\ApiResource;
102
+
use Doctrine\ORM\Mapping as ORM;
103
+
use Symfony\Component\Validator\Constraints as Assert;
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.
188
+
API Platform will handle the error returned and adapt it's format according to the API configuration. If you did configured it to respond in JSON-LD. Your response would looks like:
189
+
190
+
```json
191
+
{
192
+
"@context": "/contexts/ConstraintViolationList",
193
+
"@type": "ConstraintViolationList",
194
+
"hydra:title": "An error occurred",
195
+
"hydra:description": "properties: The product must have the minimal properties required (description, price)",
196
+
"violations": [
197
+
{
198
+
"propertyPath": "properties",
199
+
"message": "The product must have the minimal properties required (description, price)"
0 commit comments