Repository navigation
Expand file tree
/
Copy pathJsonExceptionResponseRenderer.php
More file actions
63 lines (53 loc) · 1.94 KB
/
Copy pathJsonExceptionResponseRenderer.php
File metadata and controls
63 lines (53 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
declare(strict_types=1);
namespace Arcanum\Hyper;
use Arcanum\Glitch\ArcanumException;
use Arcanum\Glitch\ExceptionRenderer;
use Arcanum\Glitch\HttpException;
use Psr\Http\Message\ResponseInterface;
/**
* Renders exceptions as JSON HTTP responses.
*
* Composes a JsonResponseRenderer to build the actual response.
* In debug mode, includes exception class, file, line, and trace.
* When verbose_errors is enabled, includes suggestion from ArcanumException.
*
* Output shape is forward-compatible with RFC 9457 Problem Details:
* `title` maps to RFC `title`, `message` maps to `detail`.
*/
class JsonExceptionResponseRenderer implements ExceptionRenderer
{
public function __construct(
private readonly JsonResponseRenderer $renderer,
private readonly bool $debug = false,
private readonly bool $verboseErrors = false,
) {
}
public function render(\Throwable $e): ResponseInterface
{
$status = match (true) {
$e instanceof HttpException => $e->getStatusCode(),
$e instanceof \Arcanum\Validation\ValidationException => StatusCode::UnprocessableEntity,
default => StatusCode::InternalServerError,
};
$payload = [
'error' => [
'status' => $status->value,
'message' => $e->getMessage(),
],
];
if ($e instanceof ArcanumException) {
$payload['error']['title'] = $e->getTitle();
if ($this->verboseErrors && $e->getSuggestion() !== null) {
$payload['error']['suggestion'] = $e->getSuggestion();
}
}
if ($this->debug) {
$payload['error']['exception'] = get_class($e);
$payload['error']['file'] = $e->getFile();
$payload['error']['line'] = $e->getLine();
$payload['error']['trace'] = $e->getTrace();
}
return $this->renderer->render($payload, status: $status);
}
}