我已经设置好配置以处理ApiController的错误功能中的错误。例如,当我转到一个不存在的页面时,它显示:message => page not found
类似于操作中定义的。但是,当我提出未经授权的请求时,该网站不会显示该操作中定义的消息,而是返回以下响应:
{
"name": "Unauthorized",
"message": "Your request was made with invalid credentials.",
"code": 0,
"status": 401,
"type": "yii\\web\\UnauthorizedHttpException"
}
我需要更改什么才能发送actionError中定义的响应?
api / config / main.php:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-api', 'httpOnly' => true],
],
'errorHandler' => [
'errorAction' => 'api/error',
],
...
api / controllers / ApiController.php:
<?php
namespace api\controllers;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\Response;
class ApiController extends Controller
{
/**
* @param $action
* @return bool
* @throws BadRequestHttpException
*/
public function beforeAction($action)
{
Yii::$app->response->format = Response::FORMAT_JSON;
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function afterAction($action, $result)
{
$session = Yii::$app->getSession();
if($session->getIsActive()) {
$session->destroy();
}
return parent::afterAction($action, $result);
}
/**
* @return array
*/
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->statusCode = $exception->statusCode;
switch($exception->statusCode)
{
case 401:
return [
'error' => 'Unauthorized',
'message' => $exception->getMessage()
];
case 404:
return [
'message' => 'Page not found'
];
default:
{
return [
'error' => 'Something went wrong',
'message' => $exception->getMessage()
];
}
}
}
}