Passed
Pull Request — master (#42)
by Paweł
04:21 queued 01:26
created

DefaultController::actionError()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nc 32
nop 0
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
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
        if (($exception = \Yii::$app->getErrorHandler()->exception) === null) {
25
            // action has been invoked not from error handler, but by direct route, so we display '404 Not Found'
26
            $exception = new NotFoundHttpException('Endpoint not found.');
27
        }
28
29
        if ($exception instanceof HttpException) {
30
            $code = $exception->statusCode;
31
        } else {
32
            $code = $exception->getCode();
33
        }
34
35
        if ($exception instanceof Exception) {
36
            $name = $exception->getName();
37
        } else {
38
            $name = 'Error';
39
        }
40
        if ($code) {
41
            $name .= " (#$code)";
42
        }
43
44
        if ($exception instanceof UserException) {
45
            $message = $exception->getMessage();
46
        } else {
47
            $message = 'An internal server error occurred.';
48
        }
49
50
        \Yii::$app->response->format = Response::FORMAT_JSON;
51
52
        return [
53
            'name' => $name,
54
            'message' => $message,
55
            'exception' => $exception,
56
        ];
57
    }
58
}
59