在PHP中显示多个异常消息

时间:2017-09-21 20:43:26

标签: php exception exception-handling try-catch

所以我正在制作这个登录应用程序,并且我在注册时显示正确的错误消息时遇到了麻烦。我希望抛出所有异常,而不仅仅是" try...catch" -method中的一个例外。

所以这就是设置:

// EXTENDED EXCEPTION CLASSES
class AException extends Exception {

  public function __construct($message = null, $code = 0) {
      echo $message;
  }
}
class BException extends Exception {

  public function __construct($message = null, $code = 0) {
      echo $message;
  }
}

// INDEX.PHP

try {

    $register = new RegisterController();

} catch (AException | BException $e) {

  $e->getMsg();
}

我有几个可能触发异常的因素,我希望触发和捕获所有异常,例如如果注册表单是空的,那么用户名为空的应该有一个例外,密码为空的另一个例外等。

class RegisterController {
    public function __construct() {
    if (!empty($_POST)) {
        $this->checkUserInput();
        $this->checkPassInput();
    }
}

//... executing code

private function checkUserInput() {
    if (strlen($_POST['username']) < 3) { // check character length bigger than 3
        throw new \AException("Username has too few characters.");
    }
}

private function checkPassInput() {
    if (strlen($_POST['password']) < 3) { // check character length bigger than 3
        throw new \BException("Password has too few characters.");
    }
}
}

那么,我如何使我的&#34; try...catch&#34; -method同时回显抛出的异常?可能吗?

现在只显示第一个抛出的异常消息,所以我想我需要找到一些方法让脚本在抛出异常后继续...

P.S。进一步澄清:如果登记表格是空的输入字段,例如用户名和密码输入都是空的,我希望代码回显两个异常消息,两者都是&#34;用户名字符太少了。&#34;和&#34;密码字符太少。&#34;。

1 个答案:

答案 0 :(得分:1)

这不是try / catch机制应该如何工作的。它并不是要向最终用户报告通知,而是在发生意外情况时以编程方式采取行动。

您想要的是一个简单的表单验证:

class RegisterController {
    public $errors = [];

    public function __construct() {
    if (!empty($_POST)) {
        $this->checkUserInput();
        $this->checkPassInput();
    }

    private function checkUserInput() {
        if (strlen($_POST['username']) < 3) { // check character length bigger than 3
            $this->errors[] = "Username has too few characters.";
        }
    }

    private function checkPassInput() {
        if (strlen($_POST['password']) < 3) { // check character length bigger than 3
            $this->errors[] = "Password has too few characters.";
        }
    }
}

然后你可以使用类似的东西:

$register = new RegisterController();
if (!empty($register->errors)) {
    foreach ($register->errors as $error) {
        echo '<div class="error">' . $error . '</div>';
    }
}
相关问题