-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
ErrorHandler.php
211 lines (187 loc) · 7.34 KB
/
ErrorHandler.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<?php
namespace FrameworkX;
use FrameworkX\Io\HtmlHandler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
use React\Promise\PromiseInterface;
/**
* @final
*/
class ErrorHandler
{
/** @var Htmlhandler */
private $html;
public function __construct()
{
$this->html = new HtmlHandler();
}
/**
* @return ResponseInterface|PromiseInterface<ResponseInterface>|\Generator
* Returns a response, a Promise which eventually fulfills with a
* response or a Generator which eventually returns a response. This
* method never throws or resolves a rejected promise. If the next
* handler fails to return a valid response, it will be turned into a
* valid error response before returning.
* @throws void
*/
public function __invoke(ServerRequestInterface $request, callable $next)
{
try {
$response = $next($request);
} catch (\Throwable $e) {
return $this->errorInvalidException($e);
}
if ($response instanceof ResponseInterface) {
return $response;
} elseif ($response instanceof PromiseInterface) {
return $response->then(function ($response) {
if ($response instanceof ResponseInterface) {
return $response;
} else {
return $this->errorInvalidResponse($response);
}
}, function ($e) {
// Promise rejected, always a `\Throwable` as of Promise v3
assert($e instanceof \Throwable || !\method_exists(PromiseInterface::class, 'catch')); // @phpstan-ignore-line
if ($e instanceof \Throwable) {
return $this->errorInvalidException($e);
} else { // @phpstan-ignore-line
// @phpstan-ignore-next-line
return $this->errorInvalidResponse(\React\Promise\reject($e)); // @codeCoverageIgnore
}
});
} elseif ($response instanceof \Generator) {
return $this->coroutine($response);
} else {
return $this->errorInvalidResponse($response);
}
}
private function coroutine(\Generator $generator): \Generator
{
do {
try {
if (!$generator->valid()) {
$response = $generator->getReturn();
if ($response instanceof ResponseInterface) {
return $response;
} else {
return $this->errorInvalidResponse($response);
}
}
} catch (\Throwable $e) {
return $this->errorInvalidException($e);
}
$promise = $generator->current();
if (!$promise instanceof PromiseInterface) {
$gref = new \ReflectionGenerator($generator);
return $this->errorInvalidCoroutine(
$promise,
$gref->getExecutingFile(),
$gref->getExecutingLine()
);
}
try {
$next = yield $promise;
} catch (\Throwable $e) {
try {
$generator->throw($e);
continue;
} catch (\Throwable $e) {
return $this->errorInvalidException($e);
}
}
try {
$generator->send($next);
} catch (\Throwable $e) {
return $this->errorInvalidException($e);
}
} while (true);
} // @codeCoverageIgnore
/** @internal */
public function requestNotFound(): ResponseInterface
{
return $this->htmlResponse(
Response::STATUS_NOT_FOUND,
'Page Not Found',
'Please check the URL in the address bar and try again.'
);
}
/**
* @internal
* @param list<string> $allowedMethods
*/
public function requestMethodNotAllowed(array $allowedMethods): ResponseInterface
{
$methods = \implode('/', \array_map(function (string $method) { return '<code>' . $method . '</code>'; }, $allowedMethods));
return $this->htmlResponse(
Response::STATUS_METHOD_NOT_ALLOWED,
'Method Not Allowed',
'Please check the URL in the address bar and try again with ' . $methods . ' request.'
)->withHeader('Allow', \implode(', ', $allowedMethods));
}
/** @internal */
public function requestProxyUnsupported(): ResponseInterface
{
return $this->htmlResponse(
Response::STATUS_BAD_REQUEST,
'Proxy Requests Not Allowed',
'Please check your settings and retry.'
);
}
private function errorInvalidException(\Throwable $e): ResponseInterface
{
$where = ' in ' . $this->where($e->getFile(), $e->getLine());
$message = '<code>' . $this->html->escape($e->getMessage()) . '</code>';
return $this->htmlResponse(
Response::STATUS_INTERNAL_SERVER_ERROR,
'Internal Server Error',
'The requested page failed to load, please try again later.',
'Expected request handler to return <code>' . ResponseInterface::class . '</code> but got uncaught <code>' . \get_class($e) . '</code> with message ' . $message . $where . '.'
);
}
/** @param mixed $value */
private function errorInvalidResponse($value): ResponseInterface
{
return $this->htmlResponse(
Response::STATUS_INTERNAL_SERVER_ERROR,
'Internal Server Error',
'The requested page failed to load, please try again later.',
'Expected request handler to return <code>' . ResponseInterface::class . '</code> but got <code>' . $this->describeType($value) . '</code>.'
);
}
/** @param mixed $value */
private function errorInvalidCoroutine($value, string $file, int $line): ResponseInterface
{
$where = ' near or before '. $this->where($file, $line) . '.';
return $this->htmlResponse(
Response::STATUS_INTERNAL_SERVER_ERROR,
'Internal Server Error',
'The requested page failed to load, please try again later.',
'Expected request handler to yield <code>' . PromiseInterface::class . '</code> but got <code>' . $this->describeType($value) . '</code>' . $where
);
}
private function where(string $file, int $line): string
{
return '<code title="See ' . $file . ' line ' . $line . '">' . \basename($file) . ':' . $line . '</code>';
}
private function htmlResponse(int $statusCode, string $title, string ...$info): ResponseInterface
{
return $this->html->statusResponse(
$statusCode,
'Error ' . $statusCode . ': ' .$title,
$title,
\implode('', \array_map(function (string $info) { return "<p>$info</p>\n"; }, $info))
);
}
/** @param mixed $value */
private function describeType($value): string
{
if ($value === null) {
return 'null';
} elseif (\is_scalar($value) && !\is_string($value)) {
return \var_export($value, true);
}
return \is_object($value) ? \get_class($value) : \gettype($value);
}
}