繁体   English   中英

Yii2 Rest Api 自定义错误响应

[英]Yii2 Rest Api customize error response

我正在使用Yii2 REST API,我正在尝试自定义error response 默认情况下,如果我在提交请求时使用了错误的凭据,我会看到:

{
    "name": "Unauthorized",
    "message": "You are requesting with an invalid credential.",
    "code": 0,
    "status": 401
}

我在哪里以及如何删除codename行?

在您的应用程序配置中尝试此代码。

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

更多详情

我有新的解决方案:

return [
    // ...
    'components' => [
        'response' => [
            'format' => yii\web\Response::FORMAT_JSON,
            'charset' => 'UTF-8',
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;

                // exception with http code != 200 and 302
                if ($response->statusCode !== 200 && $response->statusCode !== 302) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'message' => YII_DEBUG ?$response->data: 'System error'
                    ];
                    $response->statusCode = 200;
                }
                // normal response
                else{
                    // both case: controller implement Controller or ActiveController
                    $result =  [
                        'success' => isset($response->data['success'])?$response->data['success']: true
                    ];

                   // check message is set
                if (isset($response->data['message'])){
                    $result = array_merge($result, ['message' => $response->data['message']]);
                }
                else{
                    // check data is set
                    // both case: controller implement Controller or ActiveController
                    if (isset($response->data['data']))
                        $result = array_merge($result, ['data' => $response->data['data']]);
                    else{
                        $result = array_merge($result, ['data' => $response->data]);
                    }
                }

                    $response->data = $result;
                    $response->statusCode = 200;
                }
            },
        ]
    ],
];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM