1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BrainExe\Core\Middleware; |
4
|
|
|
|
5
|
|
|
use BrainExe\Core\Annotations\Middleware; |
6
|
|
|
use BrainExe\Core\Application\UserException; |
7
|
|
|
use BrainExe\Core\Traits\LoggerTrait; |
8
|
|
|
use Throwable; |
9
|
|
|
use Exception; |
10
|
|
|
use Symfony\Component\HttpFoundation\Request; |
11
|
|
|
use Symfony\Component\HttpFoundation\Response; |
12
|
|
|
use Symfony\Component\Routing\Exception\MethodNotAllowedException; |
13
|
|
|
use Symfony\Component\Routing\Exception\ResourceNotFoundException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @Middleware("Middleware.CatchUserException") |
17
|
|
|
*/ |
18
|
|
|
class CatchUserException extends AbstractMiddleware |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
use LoggerTrait; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
7 |
|
public function processException(Request $request, Throwable $exception) |
27
|
|
|
{ |
28
|
7 |
|
if ($exception instanceof ResourceNotFoundException) { |
29
|
2 |
|
$exception = new UserException(sprintf('Page not found: %s', $request->getRequestUri()), 0, $exception); |
30
|
2 |
|
$response = new Response('', 404); |
31
|
|
|
} elseif ($exception instanceof MethodNotAllowedException) { |
32
|
1 |
|
$exception = new UserException( |
33
|
|
|
sprintf( |
34
|
1 |
|
'You are not allowed to access the page. Allowed methods: %s', |
35
|
1 |
|
implode(',', $exception->getAllowedMethods()) |
36
|
|
|
), |
37
|
1 |
|
0, |
38
|
|
|
$exception |
39
|
|
|
); |
40
|
1 |
|
$response = new Response('', 405); |
41
|
|
|
} elseif ($exception instanceof UserException) { |
42
|
|
|
// just pass a UserException to Frontend |
43
|
1 |
|
$response = new Response('', 200); |
44
|
|
|
} else { |
45
|
3 |
|
$exception = new UserException($exception->getMessage(), 0, $exception); |
46
|
3 |
|
$response = new Response('', 500); |
47
|
|
|
} |
48
|
|
|
|
49
|
7 |
|
$this->error($exception->getMessage()); |
50
|
7 |
|
$this->error($exception->getTraceAsString()); |
51
|
|
|
|
52
|
7 |
|
$this->setMessage($exception, $response); |
53
|
|
|
|
54
|
7 |
|
return $response; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param Exception $exception |
59
|
|
|
* @param Response $response |
60
|
|
|
*/ |
61
|
7 |
|
protected function setMessage(Exception $exception, Response $response) |
62
|
|
|
{ |
63
|
7 |
|
$message = $exception->getMessage() ?: _('An error occurred'); |
64
|
7 |
|
$response->headers->set('X-Flash-Type', 'danger'); |
65
|
7 |
|
$response->headers->set('X-Flash-Message', $message); |
66
|
7 |
|
$response->setContent($message); |
67
|
7 |
|
} |
68
|
|
|
} |
69
|
|
|
|