-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathExceptionResponse.php
More file actions
88 lines (65 loc) · 2.39 KB
/
Copy pathExceptionResponse.php
File metadata and controls
88 lines (65 loc) · 2.39 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php declare(strict_types=1);
namespace Pdsinterop\Solid;
use Exception;
use Laminas\Diactoros\Response\HtmlResponse;
use League\Route\Http\Exception as HttpException;
use League\Route\Http\Exception\NotFoundException;
class ExceptionResponse
{
////////////////////////////// CLASS PROPERTIES \\\\\\\\\\\\\\\\\\\\\\\\\\\\
private const MESSAGE_GENERIC_ERROR = 'Yeah, that\'s an error.';
private const MESSAGE_NO_SUCH_PAGE = 'No such page.';
/** @var Exception */
private $exception;
//////////////////////////////// PUBLIC API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
final public function __construct(Exception $exception)
{
$this->exception = $exception;
}
final public function createResponse() : HtmlResponse
{
$exception = $this->exception;
if ($exception instanceof HttpException) {
$response = $this->respondToHttpException($exception);
} else {
$response = $this->responseToException($exception);
}
return $response;
}
////////////////////////////// UTILITY METHODS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private function isDevelop() : bool
{
static $isDevelop;
if ($isDevelop === null) {
$isDevelop = getenv('ENVIRONMENT') === 'development';
}
return $isDevelop;
}
private function responseToException(Exception $exception) : HtmlResponse
{
$html = "<h1>Oh-no! The developers messed up!</h1><p>{$exception->getMessage()}</p>";
if ($this->isDevelop()) {
$html .=
"<p>{$exception->getFile()}:{$exception->getLine()}</p>" .
"<pre>{$exception->getTraceAsString()}</pre>";
}
return new HtmlResponse($html, 500, []);
}
private function respondToHttpException(HttpException $exception) : HtmlResponse
{
$status = $exception->getStatusCode();
$message = self::MESSAGE_GENERIC_ERROR;
if ($exception instanceof NotFoundException) {
$message = self::MESSAGE_NO_SUCH_PAGE;
}
$html = vsprintf('<h1>%s</h1><p>%s (%s)</p>', [
$message,
$exception->getMessage(),
$status,
]);
if ($this->isDevelop()) {
$html .= "<pre>{$exception->getTraceAsString()}</pre>";
}
return new HtmlResponse($html, $status, $exception->getHeaders());
}
}