Guzzle: 无法捕获异常详细信息

Guzzle: Can't catch exception details

我正在使用 PayPal API 模拟负面响应,以便在客户通过 onApprove 方法批准付款时获得响应并正确处理付款的关键部分。

我正在使用 GuzzleHttp + Laravelcapture 客户的批准。我在完整 object 中获得 COMPLETED 状态。所以请求正常工作。

$client = new \GuzzleHttp\Client();

return
$response = $client->request(
    'POST',
    'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . $paypalOrderId . '/capture',
    [
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $access_token,
            // 'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INTERNAL_SERVER_ERROR"]),
            'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]),
        ],
    ],
);

我通过添加 header => 'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]) 来模拟响应错误,如果不在 try-catch 块内,这当然会破坏代码。

当请求没有 try-catch:

时,这是 Laravel 的输出
      "message": "Client error: `POST https://api-m.sandbox.paypal.com/v2/checkout/orders/6JE880117B631364H/capture` resulted in a `422 Unprocessable Entity` 
         response:\n{\n  \"name\": \"UNPROCESSABLE_ENTITY\",\n  \"details\": [\n    {\n      \"issue\": \"INSTRUMENT_DECLINED\",\n      \"description\": \"The (truncated...)\n",
        "exception": "GuzzleHttp\Exception\ClientException",
        "file": "C:\xampp\htdocs\react\React-Laravel\vinos-gdl\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php",
        "line": 113,

这个错误是预料之中的。因为我用 Mock-Response header.

强制它

当我在 try-catch 块中插入代码时出现“问题”。我得到了预期的 Exception 但我无法从 response:

中获得任何详细信息
catch (ServerException $e) {

    if ($e->hasResponse()) {
        return response()->json(['msg' => 'Server Error', 'error' => $e->getResponse()], 500);
    }
    return response()->json([
        'msg' => 'Server Error',
        'request' => $e->getRequest(),
        $e->hasResponse() ? $e->getResponse() : ""
    ]);

    // return response()->json(['msg' => 'Client Error', 'error' => $e->getRequest()]);
} catch (ClientException $e) {

    if ($e->hasResponse()) {
        return response()->json(['msg' => 'Client Error', 'error' => $e->getResponse()], 400);
    }
    return response()->json([
        'msg' => 'Client Error',
        'request' => $e->getRequest(),
        $e->hasResponse() ? $e->getResponse() : ""
    ]);
    // return response()->json(['msg' => 'Server Error', 'error' => report($e)]);
}
catch (BadResponseException $e){
    return response()->json(['error' => $e]);
}

这是ClientException的输出:

Error: Request failed with status code 400

{
    "msg": "Client Error",
    "error": {} // empty!!!
}

如果我强制 ServerException:

{
    "msg": "Server Error",
    "error": {} // also empty
}

Exceptions 被抛出,但是,这肯定不是正确处理错误的足够信息。我需要从 response.

中获取详细信息

前端以防有人想看:

const onApprove = (data, actions) => {
    console.log("payment approved by user", data);
    const orderID = data.orderID;

    return axios
        .post("/paypal/rest-api/capture-order", {
            orderID: orderID,
        })
        .then((res) => {
            console.log("success creating order", res.data);
        })
        .catch((err) => {
            console.error(err);
        });
};

异常应该是 BadResponseException 的一个实例,它有一个 getResponse 方法。然后您可以将响应正文转换为字符串。

$response = json_decode($ex->getResponse()->getBody()->getContents(), true);