陈诺
- 陈诺 2017-06-27 已签到连续签到2天,获得了10个金钱
@ymfhack 厉害厉害,向您学习
@ymfhack 这个可以哦!还应该去看一下yii的操作数据库,现在都是原生sql 尴尬,您是yii源码都看了么
厉害了,我的哥,回头捣鼓捣鼓
- 陈诺 回答了问题 RESTFull 错误要怎么返回json
问题总结:
RESTFull web server's error handing 里说的如果想要自定义错误响应,需要在config里添加:return [ // ... 'components' => [ 'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) { $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; $response->statusCode = 200; } }, ], ], ];
实践证明,除了给reponse添加class,on beforeSend,还需要指定format为FORMAT_JSON
具体代码如下:return [ 'response' => [ 'class' => 'yii\web\Response', 'format' => yii\web\Response::FORMAT_JSON, 'charset' => 'UTF-8', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) { $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; $response->statusCode = 200; } }, ], ]
本问题得到解答,感谢
@ymfhack /** * @return bool whether this response is successful */ public function getIsSuccessful() { return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300; }
谢谢您,真心感谢,我实现了,config里边还需要添加 format为json
'response' => [ 'class' => 'yii\web\Response', 'format' => yii\web\Response::FORMAT_JSON, 'charset' => 'UTF-8', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) { $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; $response->statusCode = 200; } }, ],