如何

2017-10-16 48 views
-1

我使用标准PHP功能捕捉PHP错误软验证:如何

try 
{ 

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

...

throw new Exception('Error Message'); 

验证数据并返回各种消息给用户。它完美的作品。但用这种方法,一切都会停止,如果新的例外被剔除(这是正确的)。但我想使用软验证(当出现错误但用户可以向前处理时)。 PHP有类似的东西吗?

+0

引发Exception的代码必须是_inside_ try块。如果这不起作用,请张贴更多的代码。 –

+0

@大卫是的。这只是一个例子 – Klapsius

+1

在我看来,解决方案已经在标题中了:为了不阻止所有事情,包含错误,您需要捕获一个异常。然后你可以决定是否继续你的程序。请更好地解释你在问什么。 – deceze

回答

1

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

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

return $errors; 
2

我认为这将帮助您了解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数据。