Skip to content

Commit 6b5f248

Browse files
doc(errors): explain how to link an Error with its ApiResource (#2154)
1 parent 9d173b4 commit 6b5f248

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

core/errors.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,3 +323,68 @@ We recommend using the `\ApiPlatform\Metadata\Exception\ProblemExceptionInterfac
323323
`\ApiPlatform\Metadata\Exception\HttpExceptionInterface`. For security reasons we add: `normalizationContext: ['ignored_attributes'
324324
=> ['trace', 'file', 'line', 'code', 'message', 'traceAsString']]` because you usually don't want these. You can override
325325
this context value if you want.
326+
327+
## Document your exceptions
328+
329+
Since 3.4, you also have the possibility to link your specific domain exceptions to your ApiResources so that they appear
330+
directly in your OpenAPI definition !
331+
332+
Let's say that you have a `Greetings` resource, and that one of its providers can throw the following exception for the
333+
`ApiPlatform\Metadata\GetCollection` Operation:
334+
335+
```php
336+
use ApiPlatform\Metadata\ErrorResource;
337+
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
338+
339+
#[ErrorResource]
340+
class MyDomainException extends \Exception implements ProblemExceptionInterface
341+
{
342+
public function getType(): string
343+
{
344+
return '/errors/418';
345+
}
346+
347+
public function getTitle(): ?string
348+
{
349+
return 'Teapot error';
350+
}
351+
352+
public function getStatus(): ?int
353+
{
354+
return 418;
355+
}
356+
357+
public function getDetail(): ?string
358+
{
359+
return $this->getMessage();
360+
}
361+
362+
public function getInstance(): ?string
363+
{
364+
return null;
365+
}
366+
367+
public string $myCustomField = 'I usually prefer coffee.';
368+
}
369+
```
370+
371+
As long as your Exception implements `ApiPlatform\Metadata\Exception\ProblemExceptionInterface` and has the `ErrorResource`
372+
attribute, you can then map it to your Operation this way:
373+
374+
```php
375+
use ApiPlatform\Metadata\ApiResource;
376+
use ApiPlatform\Metadata\GetCollection;
377+
use App\Exception\MyDomainException;
378+
379+
#[ApiResource(operations: [
380+
new GetCollection(errors: [MyDomainException::class])
381+
],
382+
)]
383+
class Greeting
384+
{
385+
}
386+
```
387+
388+
This will automatically document your potential domain exception as a Response in the OpenAPI definition, and show it in the UI :
389+
390+
![Swagger UI](images/open-api-documented-error.png)
58.4 KB
Loading

0 commit comments

Comments
 (0)