-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExceptionHandler.php
64 lines (53 loc) · 1.74 KB
/
ExceptionHandler.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
<?php
namespace Dingo\Api\Event;
use Exception;
use Dingo\Api\Http\Response;
use Dingo\Api\Exception\Handler;
use Dingo\Api\Exception\ResourceException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionHandler
{
/**
* API exception handler instance.
*
* @var \Dingo\Api\Exception\Handler
*/
protected $handler;
/**
* Create a new exception handler instance.
*
* @param \Dingo\Api\Exception\Handler $handler
* @return void
*/
public function __construct(Handler $handler)
{
$this->handler = $handler;
}
/**
* Handle an exception thrown during dispatching of an API request.
*
* @param \Exception $exception
* @return \Dingo\Api\Http\Response
* @throws \Exception
*/
public function handle(Exception $exception)
{
if ($this->handler->willHandle($exception)) {
$response = $this->handler->handle($exception);
return Response::makeFromExisting($response);
} elseif (! $exception instanceof HttpExceptionInterface) {
throw $exception;
}
if (! $message = $exception->getMessage()) {
$message = sprintf('%d %s', $exception->getStatusCode(), Response::$statusTexts[$exception->getStatusCode()]);
}
$response = ['message' => $message, 'status_code' => $exception->getStatusCode()];
if ($exception instanceof ResourceException && $exception->hasErrors()) {
$response['errors'] = $exception->getErrors();
}
if ($code = $exception->getCode()) {
$response['code'] = $code;
}
return new Response($response, $exception->getStatusCode(), $exception->getHeaders());
}
}