1 <?php
2
3 namespace Docolight\Rest\Handler;
4
5 use Yii;
6 use Exception;
7 use CErrorHandler;
8 use CInlineAction;
9 use CHttpException;
10 use CExceptionEvent;
11
12 13 14 15 16
17 class RestfulErrorHandler extends CErrorHandler
18 {
19 20 21 22 23
24 public function handle($event)
25 {
26 $controller = Yii::app()->controller;
27
28 $error = ($event instanceof CExceptionEvent) ? $event->exception : new Exception($event->message, $event->code);
29 if (!$controller) {
30 return $this->internalHandle($error);
31 }
32
33 $controller->setError($error);
34
35 return $controller->afterAction(new CInlineAction($controller, 'exception'));
36 }
37
38 39 40 41 42
43 public function internalHandle(Exception $error)
44 {
45 $data = [
46 'status' => 500,
47 'message' => 'Internal Server Error',
48 'value' => [
49 'error_code' => $error->getCode(),
50 'error_message' => strip_tags($error->getMessage()),
51 ],
52 ];
53
54 $statusCode = 500;
55
56 if ($error instanceof CHttpException) {
57 $data['status'] = 400;
58 $data['message'] = 'Bad Request';
59
60 $statusCode = 400;
61 }
62
63 if (YII_DEBUG) {
64 $data['value']['stack_trace'] = $error->getTrace();
65 }
66
67 return response('json', $statusCode, fluent($data), [], true);
68 }
69 }
70