【问题标题】:Client error 404: how to catch and gracefully handle it?客户端错误404:如何捕捉并优雅处理?
【发布时间】:2021-02-06 20:52:32
【问题描述】:

我正在使用 Symfony 5.2.1 来使用 API。

如果找不到对象(在我的例子中是一本书),API 会返回带有 404 状态的 HTTP 响应。示例输出如下:

{
    "statusCode": 404,
    "data": "Book 01986 not found"
}

当我在 Symfony 控制器中调用此 API 时(使用 Guzzle 进行客户端调用):

public function detail($bookid): Response {
        $uri = "book/$bookid";
        try {
            $res = $this->service->getService()->get($uri);
        } catch (GuzzleHttp\Exception $e) {
            echo"error";
            die();
        }
        dump($res);
        die();
        $book = json_decode((string) ($this->service->getService()->get($uri)->getBody()))->data;
        dump($book);
        die();

        return $this->render('book/detail.html.twig', ['book' => $book]);
    }

它在我的浏览器中提示如下:

我想捕捉这个错误,然后在我的前端网络应用程序中进行一些优雅的处理。

注意:当前环境设置为 DEV,而不是 PROD。

【问题讨论】:

    标签: php symfony exception guzzle


    【解决方案1】:

    您需要捕获客户端异常,您甚至可以捕获所有请求异常并通过状态码精确定位 404 异常。

     try {
              $res = $this->service->getService()->get($uri);
         } catch (\GuzzleHttp\Exception\ClientException $e) {
              if($e->hasResponse()){
                  if ($e->getResponse()->getStatusCode() == '404'){ // to pinpoint 404 errors
                      // get your 404 error message using this $e->getMessage();
                  }
              }
         }
    

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2013-08-31
      • 2017-02-12
      • 2016-09-20
      • 2018-01-01
      • 2018-03-21
      相关资源
      最近更新 更多