【问题标题】:How to catch PHP errors as soft validation如何将 PHP 错误捕获为软验证
【发布时间】:2018-03-28 03:37:13
【问题描述】:

我使用标准的PHP 函数:

try 
{ 

}
catch (Exception $exc)
  {
        echo   $exc->getMessage();
  } 

...

 throw new Exception('Error Message');

验证数据并向用户返回各种消息。而且效果很好。但是使用这种方法,如果抛出新的异常(这是正确的),一切都会停止。但我想使用软验证(当出现错误但用户可以向前处理时)。 PHP 有类似的东西吗?

【问题讨论】:

  • 抛出异常的代码必须在inside try 块中。如果这不起作用,请发布更多代码。
  • @David 是的。这只是一个插图
  • 在我看来,解决方案已经在标题中了:你catch 一个例外,以便它不会停止一切,包含错误。然后,您可以决定是否继续您的程序。请更好地解释您的要求。
  • 如果我的代码有throw new Exception 那么我想停止脚本并显示异常。但是是否存在另一种方法来显示警告等信息但不会停止执行。

标签: php error-handling try-catch


【解决方案1】:

我认为这将帮助您了解try...catch 的工作原理以及如何获取异常消息。在此处阅读有关异常的更多信息http://php.net/manual/en/language.exceptions.php

演示代码:

$exception = [];
try {
   function1();
   function2();
}
catch(Exception $e){
   $exception['msg'] = $e->getMessage();
   $exception['code'] = $e->getCode();
}

function3();
print '<pre>';
print_r($exception);
print '</pre>';

在这里,function3() 将始终被执行。但是如果 function1() 抛出异常,function2() 将不会继续执行。但是如果发生异常,您可以接收到 $exception 数据。

【讨论】:

    【解决方案2】:

    尝试将错误消息收集到一个数组中,然后返回。

    if(strlen($username) < 3) $errors[] = "Username is too short";
    if(strlen($password) < 3) $errors[] = "Password is too short";
    
    return $errors;
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多