yii2 rest api异常处理

问题描述 投票:1回答:1

我正在使用yii2 rest api模块,其中控制器类扩展了一个ActiveController,我遇到了处理错误异常的问题。当Yii REST框架使用的HTTP状态代码(如500,400)时,我需要一个正确的json响应。如果我在访问api上尝试了一个错误的方法调用,它会显示一个异常对象

object(yii\web\NotFoundHttpException)#170 (8) { ["statusCode"]=> int(404) 

在我的config / main.php中设置响应

'response' => [
    'class' => 'yii\web\Response',
    'on beforeSend' => function ($event) {
        $response = $event->sender;
        if ($response->data !== null) {
           $response->data = [
             'success' => $response->isSuccessful,
             'data' => $response->data,
           ];
          $response->statusCode = 200;
        }
    },
]

它应该显示一个msg,如:

{
    "status": 0,
    "error_code": 400,
    "message": "Bad request"
}

我尝试使用以下链接在控制器中添加行为动词:click here

我的整个应用程序基于api所以请帮助我处理所有类型的错误

php rest http exception yii2
1个回答
3
投票

还取决于你的服务器配置,但通常你不需要任何。这应该足够了:

'response' => [
    'format' => yii\web\Response::FORMAT_JSON,
    'charset' => 'UTF-8',
],

以下是使用这些配置的输出示例:https://yii2-f4a.rhcloud.com/api/tags

© www.soinside.com 2019 - 2024. All rights reserved.