0

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

$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 似乎无法捕获。我还有什么其他选择?

4

2 回答 2

1

在您的代码中收到的实际错误是 PHP 通知。你不能catch这样做,因为在那个时候它不是一个例外。Laravel 定义了该类Illuminate\Exception\Handler并使用 PHPset_error_handler()将 PHP 错误转换为 ErrorExceptions。

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

于 2013-09-07T01:20:26.693 回答
0

设置全局错误处理程序

set_exception_handler (handler);

function handler($e) {
    if($e instanceof TheExceptionYouWantToHandle) {
        //then handle it
    }
}
于 2013-09-06T21:22:30.793 回答