|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace app\modules\api\v1\controllers; |
|
4
|
|
|
|
|
5
|
|
|
use yii\base\Exception; |
|
6
|
|
|
use yii\base\UserException; |
|
7
|
|
|
use yii\web\Controller; |
|
8
|
|
|
use yii\web\HttpException; |
|
9
|
|
|
use yii\web\NotFoundHttpException; |
|
10
|
|
|
use yii\web\Response; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Default controller for the `v1` module |
|
14
|
|
|
*/ |
|
15
|
|
|
class DefaultController extends Controller |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Generic error. |
|
19
|
|
|
* |
|
20
|
|
|
* @return array |
|
21
|
|
|
*/ |
|
22
|
|
|
public function actionError() |
|
23
|
|
|
{ |
|
24
|
|
|
$exception = $this->getException(); |
|
25
|
|
|
|
|
26
|
|
|
$name = $this->getName($exception); |
|
27
|
|
|
|
|
28
|
|
|
$message = $this->getMessage($exception); |
|
29
|
|
|
|
|
30
|
|
|
return $this->prepareResponse($name, $message, $exception); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
protected function getException() |
|
34
|
|
|
{ |
|
35
|
|
|
if (($exception = \Yii::$app->getErrorHandler()->exception) === null) { |
|
36
|
|
|
// action has been invoked not from error handler, but by direct route, so we display '404 Not Found' |
|
37
|
|
|
$exception = new NotFoundHttpException('Endpoint not found.'); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
return $exception; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
protected function getCode(Exception $exception): int |
|
44
|
|
|
{ |
|
45
|
|
|
if ($exception instanceof HttpException) { |
|
46
|
|
|
$code = $exception->statusCode; |
|
47
|
|
|
} else { |
|
48
|
|
|
$code = $exception->getCode(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return $code; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
protected function getName(Exception $exception): string |
|
55
|
|
|
{ |
|
56
|
|
|
if ($exception instanceof Exception) { |
|
|
|
|
|
|
57
|
|
|
$name = $exception->getName(); |
|
58
|
|
|
} else { |
|
59
|
|
|
$name = 'Error'; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$code = $this->getCode($exception); |
|
63
|
|
|
|
|
64
|
|
|
if ($code) { |
|
65
|
|
|
$name .= " (#$code)"; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $name; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
protected function getMessage(Exception $exception): string |
|
72
|
|
|
{ |
|
73
|
|
|
if ($exception instanceof UserException) { |
|
74
|
|
|
$message = $exception->getMessage(); |
|
75
|
|
|
} else { |
|
76
|
|
|
$message = 'An internal server error occurred.'; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return $message; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
protected function prepareResponse($name, $message, $exception): array |
|
83
|
|
|
{ |
|
84
|
|
|
\Yii::$app->response->format = Response::FORMAT_JSON; |
|
85
|
|
|
|
|
86
|
|
|
return [ |
|
87
|
|
|
'name' => $name, |
|
88
|
|
|
'message' => $message, |
|
89
|
|
|
'exception' => $exception, |
|
90
|
|
|
]; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|