Handling Soap timeouts in PHP

前端 未结 8 1914
囚心锁ツ
囚心锁ツ 2021-01-30 09:05

I\'m working on a project where I am verifying information from a user with a SOAP web service. I currently am taking care of errors assuming that I\'m receiving responses from

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 09:52

    I used two factors to get my SoapClient extention to throw a nice exception. The message and the time the request took to return. I think the error message "Error Fetching http headers" can also occure in some other cases, therefore the time check.

    The following code should be about right

    class SoapClientWithTimeout extends SoapClient {
        public function __soapCall ($params, ---) {
            $time_start = microtime(true);
            try {
                $result = parent::__soapCall ($params, ---);
            }
            catch (Exception $e) {
                $time_request = (microtime(true)-$time_start);
                if(
                    $e->getMessage() == 'Error Fetching http headers' &&
                    ini_get('default_socket_timeout') < $time_request
                ) {
                    throw new SoapTimeoutException(
                        'Soap request most likly timed out.'.
                        ' It took '.$time_request.
                        ' and the limit is '.ini_get('default_socket_timeout')
                    );
                }
    
                // E: Not a timeout, let's rethrow the original exception
                throw $e;
            }
    
            // All good, no exception from the service or PHP
            return $result;
        }
    }
    
    class SoapTimeoutException extends Exception {}
    

    I then use SoapClientWithTimeout

    $client = new SoapClientWithTimeout();
    try {
        $response = $client->SomeSoapRequest();
        var_dump($response);
    }
    catch(SoapTimeoutException $e){
        echo 'We experienced a timeout! '. $e->getMessage();
    }
    catch(Exception $e) {
        echo 'Exception: '.$e->getMessage();
    }
    

    To debug your service timing out. Add the following line before calling the service

    ini_set('default_socket_timeout', 1);
    

提交回复
热议问题