PHP SOAP error catching

后端 未结 7 1323
北恋
北恋 2020-12-14 07:49

I\'m getting desperate, all I want is simple error handling when the PHP SOAP Web Service is down to echo an error message login service down. Please help me!

7条回答
  •  遥遥无期
    2020-12-14 08:20

    UPDATE July 2018

    If you don't care about getting the SoapFault details and just want to catch any errors coming from the SoapClient you can catch "Throwable" in PHP 7+. The original problem was that SoapClient can "Fatal Error" before it throws a SoapFault so by catching both errors and exceptions with Throwable you will have very simple error handling e.g.

    try{
        soap connection...
    }catch(Throwable $e){
        echo 'sorry... our service is down';
    }
    

    If you need to catch the SoapFault specifically, try the original answer which should allow you to suppress the fatal error that prevents the SoapFault being thrown

    Original answer relevant for older PHP versions

    SOAP can fatal error calling the native php functions internally which prevents the SoapFaults being thrown so we need to log and suppress those native errors.

    First you need to turn on exceptions handling:

    try {
        $client = new SoapClient("http://192.168.0.142:8080/services/Logon?wsdl",array(
           'exceptions' => true,
        ));
    } catch ( SoapFault $e ) { // Do NOT try and catch "Exception" here
        echo 'sorry... our service is down';
    }
    

    AND THEN you also need to silently suppress any "PHP errors" that originate from SOAP using a custom error handler:

    set_error_handler('handlePhpErrors');
    function handlePhpErrors($errno, $errmsg, $filename, $linenum, $vars) {
        if (stristr($errmsg, "SoapClient::SoapClient")) {
             error_log($errmsg); // silently log error
             return; // skip error handling
        }
    }
    

    You will then find it now instead trips a SoapFault exception with the correct message "Soap error: SOAP-ERROR: Parsing WSDL: Couldn't load from '...'" and so you end up back in your catch statement able to handle the error more effectively.

提交回复
热议问题