如何在 PHP 中处理此 ErrorException


How to handle this ErrorException in PHP

我正在尝试使用以下代码格式化用户输入:

$userInput="blalalbla";//assume the user is inputing wrong data, they are supposed to input it like "12:30"
try{
  $timeStr=explode(":",$userInput);
  $time=(new Datetime())->setTime($timeStr[0],$timeStr[1]);
}catch(ErrorException $e){
}

但是,如果输入的格式不正确,laravel4 将始终触发 ErrorException,我无法捕获它。由于用户输入可能以不同的方式出错,我认为这是处理验证的最优雅的方式。尽管听起来很荒谬,但ErrorExceptions似乎无法捕获。我还有哪些其他选择?

代码中收到的实际错误是 PHP 通知。您无法catch它,因为它在那个时间点不是例外。Laravel定义了类Illuminate'Exception'Handler,并使用PHP的set_error_handler()将PHP错误转换为ErrorExceptions。

若要在控制器中使用 try/catch 块,必须自己在该区域中引发异常(或使用引发异常的代码)。但是,正如大多数人所评论的那样,在任何代码中实际使用输入之前,您应该进行适当的输入检查和清理。糟糕的输入是否引发异常完全取决于您。

设置全局错误处理程序

set_exception_handler (handler);
function handler($e) {
    if($e instanceof TheExceptionYouWantToHandle) {
        //then handle it
    }
}