划分PHP错误和应用程序错误 [英] Divide PHP errors and Application Errors
问题描述
我在处理应用程序并发生问题。我正在考虑让PHP错误(他们将登录数据库或文件)并管理其他错误(例如您的用户名无效或您输入的密码错误或图像无法加载)与着名的try-catch方法。只有使用try-catch才能完全管理这种错误吗?
I'm working on an Application and a question occurred. I was thinking of letting PHP errors a side (they would be log in the database or in a file) and manage other errors (such as "Your username is not valid" or "Your typed the wrong password" or "The image could not be loaded") with the so famous try-catch method. Is it good to completely manage this kind of errors only with try-catch?
推荐答案
异常的主要优点是它的行为smallite mort,一个本地的 die()
里面的 try {}
块,阻止进一步的代码执行。
The main advantage of exceptions is it's behavior of "petite mort", a local die()
inside try{}
block, preventing further code from execution.
虽然处理应用程序错误非常方便,但在处理验证用户输入时变得不那么好。如果一个用户填写了3个错误填写表单,那么就可以一次性地将它们全部显示出来,而不是一个接一个地显示出来。
While it's quite handy in handling application errors, it become not so good when dealing with validating user input. If a user made 3 mistakes filling a form, it would be merciful to show them all at once, not one after another.
您更需要POST / Redirect / GET模式来处理用户错误:
You rather need POST/Redirect/GET pattern to handle user errors:
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
//if no errors - saving data and redirect
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
这篇关于划分PHP错误和应用程序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!