1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\ErrorHandler; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use Psr\Log\NullLogger; |
11
|
|
|
|
12
|
|
View Code Duplication |
final class SimpleErrorHandler implements ErrorHandlerInterface |
|
|
|
|
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ErrorResponseProviderInterface |
16
|
|
|
*/ |
17
|
|
|
private $provider; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var LoggerInterface |
21
|
|
|
*/ |
22
|
|
|
private $logger; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param ErrorResponseProviderInterface $provider |
26
|
|
|
*/ |
27
|
|
|
public function __construct(ErrorResponseProviderInterface $provider, LoggerInterface $logger = null) |
28
|
|
|
{ |
29
|
|
|
$this->provider = $provider; |
30
|
|
|
$this->logger = $logger ?? new NullLogger(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param Request $request |
35
|
|
|
* @param Response $response |
36
|
|
|
* @param \Exception $exception |
37
|
|
|
* |
38
|
|
|
* @return Response |
39
|
|
|
*/ |
40
|
|
|
public function __invoke(Request $request, Response $response, \Exception $exception): Response |
41
|
|
|
{ |
42
|
|
|
$this->logException($exception); |
43
|
|
|
|
44
|
|
|
return $this->provider->get($request, $response, $exception); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param \Exception $exception |
49
|
|
|
*/ |
50
|
|
|
private function logException(\Exception $exception) |
51
|
|
|
{ |
52
|
|
|
if ($exception instanceof HttpException) { |
53
|
|
|
$this->logger->warning( |
54
|
|
|
'error-handler: {code} {message}', |
55
|
|
|
['status' => $exception->getCode(), 'message' => $exception->getMessage()] |
56
|
|
|
); |
57
|
|
|
|
58
|
|
|
return; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$this->logger->error( |
62
|
|
|
'error-handler: {code} {message}', |
63
|
|
|
['status' => 500, 'message' => $exception->getMessage()] |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.