客户端错误404:如何捕获并优雅地处理它?

Tay*_*orR 1 php exception symfony guzzle

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

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

{
    "statusCode": 404,
    "data": "Book 01986 not found"
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当我在 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]);
    }
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

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

bhu*_*cho 6

您需要捕获客户端异常,您甚至可以捕获所有请求异常并通过状态码精确定位 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();
              }
          }
     }
Run Code Online (Sandbox Code Playgroud)