forked from slimphp/Slim
/
ErrorHandler.php
309 lines (269 loc) · 8.88 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<?php
/**
* Slim Framework (https://slimframework.com)
*
* @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
declare(strict_types=1);
namespace Slim\Handlers;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Slim\Error\Renderers\HtmlErrorRenderer;
use Slim\Error\Renderers\JsonErrorRenderer;
use Slim\Error\Renderers\PlainTextErrorRenderer;
use Slim\Error\Renderers\XmlErrorRenderer;
use Slim\Exception\HttpException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Interfaces\CallableResolverInterface;
use Slim\Interfaces\ErrorHandlerInterface;
use Slim\Interfaces\ErrorRendererInterface;
use Throwable;
/**
* Default Slim application error handler
*
* It outputs the error message and diagnostic information in one of the following formats:
* JSON, XML, Plain Text or HTML based on the Accept header.
*/
class ErrorHandler implements ErrorHandlerInterface
{
/**
* @var string
*/
protected $defaultErrorRendererContentType = 'text/html';
/**
* @var ErrorRendererInterface|string|callable
*/
protected $defaultErrorRenderer = HtmlErrorRenderer::class;
/**
* @var array
*/
protected $errorRenderers = [
'application/json' => JsonErrorRenderer::class,
'application/xml' => XmlErrorRenderer::class,
'text/xml' => XmlErrorRenderer::class,
'text/html' => HtmlErrorRenderer::class,
'text/plain' => PlainTextErrorRenderer::class,
];
/**
* @var bool
*/
protected $displayErrorDetails;
/**
* @var bool
*/
protected $logErrors;
/**
* @var bool
*/
protected $logErrorDetails;
/**
* @var string|null
*/
protected $contentType;
/**
* @var string
*/
protected $method;
/**
* @var ServerRequestInterface
*/
protected $request;
/**
* @var Throwable
*/
protected $exception;
/**
* @var int
*/
protected $statusCode;
/**
* @var CallableResolverInterface
*/
protected $callableResolver;
/**
* @var ResponseFactoryInterface
*/
protected $responseFactory;
/**
* @param CallableResolverInterface $callableResolver
* @param ResponseFactoryInterface $responseFactory
*/
public function __construct(CallableResolverInterface $callableResolver, ResponseFactoryInterface $responseFactory)
{
$this->callableResolver = $callableResolver;
$this->responseFactory = $responseFactory;
}
/**
* Invoke error handler
*
* @param ServerRequestInterface $request The most recent Request object
* @param Throwable $exception The caught Exception object
* @param bool $displayErrorDetails Whether or not to display the error details
* @param bool $logErrors Whether or not to log errors
* @param bool $logErrorDetails Whether or not to log error details
*
* @return ResponseInterface
*/
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
$this->displayErrorDetails = $displayErrorDetails;
$this->logErrors = $logErrors;
$this->logErrorDetails = $logErrorDetails;
$this->request = $request;
$this->exception = $exception;
$this->method = $request->getMethod();
$this->statusCode = $this->determineStatusCode();
if ($this->contentType === null) {
$this->contentType = $this->determineContentType($request);
}
if ($logErrors) {
$this->writeToErrorLog();
}
return $this->respond();
}
/**
* Force the content type for all error handler responses.
*
* @param string|null $contentType The content type
*/
public function forceContentType(?string $contentType): void
{
$this->contentType = $contentType;
}
/**
* @return int
*/
protected function determineStatusCode(): int
{
if ($this->method === 'OPTIONS') {
return 200;
}
if ($this->exception instanceof HttpException) {
return $this->exception->getCode();
}
return 500;
}
/**
* Determine which content type we know about is wanted using Accept header
*
* Note: This method is a bare-bones implementation designed specifically for
* Slim's error handling requirements. Consider a fully-feature solution such
* as willdurand/negotiation for any other situation.
*
* @param ServerRequestInterface $request
* @return string
*/
protected function determineContentType(ServerRequestInterface $request): ?string
{
$acceptHeader = $request->getHeaderLine('Accept');
$selectedContentTypes = array_intersect(
explode(',', $acceptHeader),
array_keys($this->errorRenderers)
);
$count = count($selectedContentTypes);
if ($count) {
$current = current($selectedContentTypes);
/**
* Ensure other supported content types take precedence over text/plain
* when multiple content types are provided via Accept header.
*/
if ($current === 'text/plain' && $count > 1) {
return next($selectedContentTypes);
}
return $current;
}
if (preg_match('/\+(json|xml)/', $acceptHeader, $matches)) {
$mediaType = 'application/' . $matches[1];
if (array_key_exists($mediaType, $this->errorRenderers)) {
return $mediaType;
}
}
return null;
}
/**
* Determine which renderer to use based on content type
*
* @return callable
*
* @throws RuntimeException
*/
protected function determineRenderer(): callable
{
if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) {
$renderer = $this->errorRenderers[$this->contentType];
} else {
$renderer = $this->defaultErrorRenderer;
}
return $this->callableResolver->resolve($renderer);
}
/**
* Register an error renderer for a specific content-type
*
* @param string $contentType The content-type this renderer should be registered to
* @param ErrorRendererInterface|string|callable $errorRenderer The error renderer
*/
public function registerErrorRenderer(string $contentType, $errorRenderer): void
{
$this->errorRenderers[$contentType] = $errorRenderer;
}
/**
* Set the default error renderer
*
* @param string $contentType The content type of the default error renderer
* @param ErrorRendererInterface|string|callable $errorRenderer The default error renderer
*/
public function setDefaultErrorRenderer(string $contentType, $errorRenderer): void
{
$this->defaultErrorRendererContentType = $contentType;
$this->defaultErrorRenderer = $errorRenderer;
}
/**
* Write to the error log if $logErrors has been set to true
*
* @return void
*/
protected function writeToErrorLog(): void
{
$renderer = new PlainTextErrorRenderer();
$error = $renderer->__invoke($this->exception, $this->logErrorDetails);
$error .= "\nView in rendered output by enabling the \"displayErrorDetails\" setting.\n";
$this->logError($error);
}
/**
* Wraps the error_log function so that this can be easily tested
*
* @param string $error
* @return void
*/
protected function logError(string $error): void
{
error_log($error);
}
/**
* @return ResponseInterface
*/
protected function respond(): ResponseInterface
{
$response = $this->responseFactory->createResponse($this->statusCode);
if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) {
$response = $response->withHeader('Content-type', $this->contentType);
} else {
$response = $response->withHeader('Content-type', $this->defaultErrorRendererContentType);
}
if ($this->exception instanceof HttpMethodNotAllowedException) {
$allowedMethods = implode(', ', $this->exception->getAllowedMethods());
$response = $response->withHeader('Allow', $allowedMethods);
}
$renderer = $this->determineRenderer();
$body = call_user_func($renderer, $this->exception, $this->displayErrorDetails);
$response->getBody()->write($body);
return $response;
}
}