如何覆盖异常 Class 而不显示致命错误

How to override the Exception Class and not to display the Fatal error

我正在尝试编写与 API 通信的 class。我想将 PHP 中的标准异常 class 覆盖为 return 我想要的消息和错误代码。

我已经添加了这个扩展

<?php namespace API;

/**
 * API Exception
 *
 * @package ICWS
 */
class ApiException extends \Exception
{
    public function __construct($message, $code = 0)
    {
        // Custom ICWS API Exception Message
        $apiMessage = 'ICWS API Error: ' . $message;

        //More code to come to custom the error message/code.....

        // Run parent construct using custom message
        parent::__construct($apiMessage, $code);
    }
}
?> 

然后在需要时我会像这样创建新的 ApiException

    throw new ApiException($errorMessage, $errorNo);

最后我把抛出异常的函数用try{} catch()块包裹起来捕获异常

但是,我仍然收到 fatal error 而不仅仅是我提供的消息。

这是我的代码

public function createSession($userID, $password){

    $data = array('userID' => $userID,
                  'password' => $password);

    try {

        $data = $this->_makeCall('POST', 'connection', $data);

        $this->_csrfToken = $data['csrfToken'];
        $this->_sessionId = $data['sessionId'];
        $this->_alternateHostList = $data['alternateHostList'];

    } catch (Exception $e){
        $this->_displayError($e);
    }
}

private function _makeCall($uri, $data = false, $header = array())
{
    $ch = curl_init();
    $url = $this->_baseURL . $uri;

    //disable the use of cached connection
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);

    curl_setopt($ch, CURLOPT_URL, $url);

    //return the respond from the API
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if(!empty($header)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    curl_setopt($ch, CURLOPT_POST, true);

    if ($data){
        $JSON = json_encode( $data );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $JSON );
    }


    $result = curl_exec($ch);

    //throw cURL exception
    if($result === false){
        $errorNo = curl_errno($ch);
        $errorMessage = curl_error($ch);

        throw new ApiException($errorMessage, $errorNo);
    }   

    $result = json_decode($result, true);

    //throw API exception
    if(  $this->_hasAPIError($result) )
    ){          
        throw new ApiException($result['message'], 0);
    }

    return $result;
}

private function _displayError(Exception $e){
    echo 'Error Number: ' . $e->getCode() . "\n";
    echo 'Error Description: ' . $e->getMessage() . "\n\n";     
}

private function _hasAPIError($result){
    if(    isset($result['errorId']) && !empty($result['errorId'])
        && isset($result['errorCode']) && !empty($result['errorCode'])
        && isset($result['message']) && !empty($result['message'])
    ){          
        return true;
    }

    return false;       
}

我想在最后看到这样的东西 "if there is an error"

Error Number: 0
Error Description: ICWS API Error: The authentication process failed

这是我目前得到的

Fatal error: Uncaught exception 'API\ApiException' with message 'ICWS API Error: The authentication process failed.' in C:\phpsites\icws\API\ICWS.php:130 Stack trace: #0 C:\phpsites\icws\API\ICWS.php(57): API\ICWS->_makeCall('connection', Array) #1 C:\phpsites\icws\index.php(17): API\ICWS->createSession('user', 'pass') #2 {main} thrown in C:\phpsites\icws\API\ICWS.php on line 130

错误是您捕获的是 Exception,而不是 ApiException。试试这个:

try {
    $data = $this->_makeCall('POST', 'connection', $data);
    $this->_csrfToken = $data['csrfToken'];
    $this->_sessionId = $data['sessionId'];
    $this->_alternateHostList = $data['alternateHostList'];
} catch (ApiException $e){ // Here is the change: Exception to ApiException
    $this->_displayError($e);
}

没有将 Exception class 导入到您的命名空间中,因此在执行catch (Exception $e) 时,Exception 是一个未知 class(因为 PHP 假设 API\Exception)并且 PHP 不会注意到 APIExceptionException 的子 class .奇怪的是,PHP 不会抱怨捕捉到一个不存在的 class(我刚刚在本地用 PHP 5.6.8 确认了这一点)。

以下应该有效:

catch (\Exception $e) {
    // ...
}

或者:

use Exception;
// ...
catch (\Exception $e) {
    // ...
}