1 | <?php |
||
19 | class CatchUserException extends AbstractMiddleware |
||
20 | { |
||
21 | |||
22 | const ERROR_NOT_AUTHORIZED = 'NotAuthorized'; |
||
23 | |||
24 | use TranslationTrait; |
||
25 | |||
26 | /** |
||
27 | * @var Logger |
||
28 | */ |
||
29 | private $logger; |
||
30 | |||
31 | /** |
||
32 | * @Inject("@logger") |
||
33 | * @param Logger $logger |
||
34 | */ |
||
35 | 13 | public function __construct(Logger $logger) |
|
39 | |||
40 | /** |
||
41 | * {@inheritdoc} |
||
42 | */ |
||
43 | 13 | public function processException(Request $request, Throwable $exception) |
|
44 | { |
||
45 | 13 | if ($exception instanceof ResourceNotFoundException) { |
|
46 | 3 | $exception = new UserException( |
|
47 | 3 | $this->translate( |
|
48 | 3 | 'Page not found: %s', |
|
49 | 3 | htmlspecialchars($request->getRequestUri()) |
|
50 | ), |
||
51 | 3 | 0, |
|
52 | 3 | $exception |
|
53 | ); |
||
54 | 3 | $response = new Response('', 404); |
|
55 | 10 | } elseif ($exception instanceof MethodNotAllowedException) { |
|
56 | 2 | $exception = new UserException( |
|
57 | 2 | $this->translate( |
|
58 | 2 | 'You are not allowed to access the page. Allowed methods: %s', |
|
59 | 2 | implode(',', $exception->getAllowedMethods()) |
|
60 | ), |
||
61 | 2 | 0, |
|
62 | 2 | $exception |
|
63 | ); |
||
64 | 2 | $response = new Response('', 405); |
|
65 | 2 | $response->headers->set('X-Error', self::ERROR_NOT_AUTHORIZED); |
|
66 | 8 | } elseif ($exception instanceof UserException) { |
|
67 | // just pass a UserException to Frontend |
||
68 | 2 | $response = new Response('', 200); |
|
69 | } else { |
||
70 | 6 | $exception = new UserException($exception->getMessage(), 0, $exception); |
|
71 | 6 | $response = new Response('', 500); |
|
72 | } |
||
73 | |||
74 | 13 | $this->logger->error($exception->getMessage()); |
|
75 | 13 | $this->logger->error($exception->getTraceAsString()); |
|
76 | |||
77 | 13 | $this->setMessage($exception, $request, $response); |
|
78 | |||
79 | 13 | return $response; |
|
80 | } |
||
81 | |||
82 | /** |
||
83 | * @param Throwable $exception |
||
84 | * @param Request $request |
||
85 | * @param Response $response |
||
86 | */ |
||
87 | 13 | private function setMessage(Throwable $exception, Request $request, Response $response) |
|
98 | } |
||
99 |