How to handle Fatal error: cURL error 7: Failed to connect to xxxx port 443

How to handle Fatal error: cURL error 7: Failed to connect to xxxx port 443

我有一个连接到第三方的脚本 API。它是并且应该是 运行 24/7 不间断循环(我在重新启动循环之前在最后使用睡眠)。

问题是有时第三方 API 被关闭或者连接简单地断开并出现以下错误:

Fatal error: Uncaught exception 'GuzzleHttp\Ring\Exception\ConnectException' with message 'cURL error 7: Failed to connect to xxx.com port 443

有没有什么方法可以 "break" 解决这个致命错误以确保代码重新启动并在可以执行操作时继续,或者我必须在每次收到此错误时手动重新启动?

来自Michael's

it looks like you can just catch the GuzzleHttp\Ring\Exception\ConnectException exception

像这样:

use GuzzleHttp\Ring\Exception\ConnectException;

try {
    // the code which throws the error
} catch( ConnectException $ex ) {
    switch ( $ex->getMessage() ) {
        case '7': // to be verified
            // handle your exception in the way you want,
            // maybe with a graceful fallback
            break;
    }
}

它似乎是 guzzle 的 ConnectException extends some classes and ultimately extends php's Exception,因此您可以安全地使用 getCode() 方法,让您能够捕获一个标识符,您可以根据您的需要做出相应的反应。