-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
HandleErrors.php
56 lines (49 loc) · 1.67 KB
/
HandleErrors.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
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Http\Middleware;
use Flarum\Foundation\ErrorHandling\HttpFormatter;
use Flarum\Foundation\ErrorHandling\Registry;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Throwable;
/**
* Catch exceptions thrown in a PSR-15 middleware stack and handle them safely.
*
* All errors will be rendered using the provided formatter. In addition,
* unknown errors will be passed on to one or multiple
* {@see \Flarum\Foundation\ErrorHandling\Reporter} instances.
*/
class HandleErrors implements Middleware
{
public function __construct(
protected Registry $registry,
protected HttpFormatter $formatter,
/** @var \Flarum\Foundation\ErrorHandling\Reporter[] $reporters */
protected iterable $reporters
) {
}
/**
* Catch all errors that happen during further middleware execution.
*/
public function process(Request $request, Handler $handler): Response
{
try {
return $handler->handle($request);
} catch (Throwable $e) {
$error = $this->registry->handle($e);
if ($error->shouldBeReported()) {
foreach ($this->reporters as $reporter) {
$reporter->report($error->getException());
}
}
return $this->formatter->format($error, $request);
}
}
}