YII2 API接口格式化返回数据配置,统一拦截异常,在配置文件 main.php
'response' => ['class' => 'yii\web\Response','on beforeSend' => function ($event) {$response = $event->sender;$code = $response->statusCode;$data = ['code' => $code == 200 ? 0 : -1,'status' => $code];$data['msg'] = $code >= 400 ? Yii::$app->getErrorHandler()->exception->getMessage() : 'OK';if ($code == 200) {$data['data'] = $response->data;}$response->data = $data;$response->statusCode = 200;$response->format = \yii\web\Response::FORMAT_JSON;},],