PHP自定义错误处理程序:如何确定是否在try {} catch {}块中生成了异常?

时间:2015-08-07 15:21:20

标签: php error-handling try-catch

我有一个自定义错误处理程序:

set_error_handler('API_Error_Handler');
register_shutdown_function('Fatal_Error_Handler'); // This one calls API_Error_Handler eventually

在以下示例中,catch{}部分和API_Error_Handler都已执行。

try{
  // Exception raised here
} catch(Exception $e){
  // No error reporting needed, do something else
}

我只想执行catch{}。我怎么做?也许在API_Error_Handler内确定是否已经通过try-catch捕获了异常?或者还有其他方法吗?

示例代码:

set_error_handler(function() {
  echo "Error is handled by custom error handler. <br>"; 
});

try{
  new SoapClient('http://bad.address/wsdl');
} catch(Exception $e){
  echo "Error is caught. <br>";
}

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是自己创建一个Exception类,扩展Exception:

var app = angular.module('myApp', []);

app.controller('Controller',  function ($scope, $interval) {
    $scope.myValue = "first";
    console.log($scope.myValue);

    setTimeout(function() { 
        $scope.myValue = "second";  // never updates
        console.log($scope.myValue);
        $scope.$emit("my-event", "third"); // never updates
        console.log($scope.myValue);
        $interval(function() {
            $scope.$emit('my-event', "fourth");
        }, 1000, 1);
    }, 1000);

    $interval(function() {
        $scope.myValue = "fifth";
        console.log($scope.myValue);
        $interval(function() {        
            $scope.$emit("my-event", "sixth");
        }, 1000, 1);
    }, 3000, 1);

    $scope.$on('my-event', function (event, arg) {
        $scope.myValue = arg;
        console.log(arg);
    });
});

并将其扔到您需要的地方。然后改变

class MyCustomException extends \Exception {}

} catch (Exception $e)

并且您应该只捕获自定义异常