错误处理

有时你希望自定义默认的错误处理格式。例如,我们需要知道响应时间戳,以及响应是否是成功的。框架提供了一个很简单的方式来做到这点。

准备

重复创建一个REST服务器小节中准备如何做…的所有步骤。

如何做…

为了达到这个目标,你可以响应@app/config/web.php中的respond to the beforeSend event of the response组件:

  1. 'response' => [
  2. 'class' => 'yii\web\Response',
  3. 'on beforeSend' => function ($event) {
  4. $response = $event->sender;
  5. if ($response->data !== null) {
  6. $response->data = [
  7. 'success' => $response->isSuccessful,
  8. 'timestamp' => time(),
  9. 'path' => Yii::$app->request->getPathInfo(),
  10. 'data' => $response->data,
  11. ];
  12. }
  13. },
  14. ],

工作原理…

为了了解代码中发生了什么,我们来试一下。首先,在控制台中运行如下代码:

  1. curl -i "http://yii-book.app/films/1"

你将得到如下输出:

  1. HTTP/1.1 200 OK
  2. Date: Thu, 24 Sep 2015 04:24:52 GMT
  3. Server: Apache
  4. X-Powered-By: PHP/5.5.23
  5. Content-Length: 115
  6. Content-Type: application/json; charset=UTF-8
  7. {"success":true,"timestamp":1443068692,"path":"films/
  8. 1","data":{"id":1,"title":"Interstellar","release_year":2014}}

然后,在控制台中运行如下代码:

  1. curl -i "http://yii-book.app/films/1000"

你将得到如下代码:

  1. HTTP/1.1 404 Not Found
  2. Date: Thu, 24 Sep 2015 04:24:26 GMT
  3. Server: Apache
  4. X-Powered-By: PHP/5.5.23
  5. Content-Length: 186
  6. Content-Type: application/json; charset=UTF-8
  7. {"success":false,"timestamp":1443068666,"path":"films/
  8. 1000","data":{"name":"Not Found","message":"Object not found:
  9. 1000","code":0,"status":404,"type":"yii\\web\\NotFoundHttpException"}
  10. }

我们在发送响应内容前做了修改。这中方法很容易定义响应是否成功。

参考

欲了解更多信息,参考http://www.yiiframework.com/doc-2.0/guide-rest-error-handling.html