-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpErrorHandler.php
77 lines (65 loc) · 2.76 KB
/
HttpErrorHandler.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
<?php
declare(strict_types=1);
namespace App\Application\Handlers;
use App\Application\Actions\ActionError;
use App\Application\Actions\ActionPayload;
use JimTools\JwtAuth\Exceptions\AuthorizationException;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Exception\HttpBadRequestException;
use Slim\Exception\HttpException;
use Slim\Exception\HttpForbiddenException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Slim\Exception\HttpNotImplementedException;
use Slim\Exception\HttpUnauthorizedException;
use Slim\Handlers\ErrorHandler as SlimErrorHandler;
use Throwable;
class HttpErrorHandler extends SlimErrorHandler
{
/**
* @inheritdoc
*/
protected function respond(): Response
{
$exception = $this->exception;
$statusCode = 500;
$error = new ActionError(
ActionError::SERVER_ERROR,
'An internal error has occurred while processing your request.'
);
if ($exception instanceof HttpException) {
$statusCode = $exception->getCode();
$error->setDescription($exception->getMessage());
if ($exception instanceof HttpNotFoundException) {
$error->setType(ActionError::RESOURCE_NOT_FOUND);
} elseif ($exception instanceof HttpMethodNotAllowedException) {
$error->setType(ActionError::NOT_ALLOWED);
} elseif ($exception instanceof HttpUnauthorizedException) {
$error->setType(ActionError::UNAUTHENTICATED);
} elseif ($exception instanceof HttpForbiddenException) {
$error->setType(ActionError::INSUFFICIENT_PRIVILEGES);
} elseif ($exception instanceof HttpBadRequestException) {
$error->setType(ActionError::BAD_REQUEST);
} elseif ($exception instanceof HttpNotImplementedException) {
$error->setType(ActionError::NOT_IMPLEMENTED);
}
}
if (
!($exception instanceof HttpException)
&& $exception instanceof Throwable
&& $this->displayErrorDetails
) {
$error->setDescription($exception->getMessage());
}
if ($exception instanceof AuthorizationException) {
$statusCode = 401;
$error->setType(ActionError::UNAUTHENTICATED);
$error->setDescription('You are not authentication, please sign in.');
}
$payload = new ActionPayload($statusCode, null, $error);
$encodedPayload = json_encode($payload, JSON_PRETTY_PRINT);
$response = $this->responseFactory->createResponse($statusCode);
$response->getBody()->write($encodedPayload);
return $response->withHeader('Content-Type', 'application/json');
}
}