【问题标题】:How to return errors from PHP method?如何从 PHP 方法返回错误?
【发布时间】:2013-09-29 13:40:51
【问题描述】:

我的 User 类中有一个保存方法。

如果 save 方法遇到验证错误,它会返回我向用户显示的错误数组。然而,这意味着在我的代码中我必须编写:

if (!$user->save()) {
   //display success to user
}

当然,我的 save 方法应该在成功时返回 true。但是在这种情况下我该如何处理错误呢?

【问题讨论】:

  • 混合返回。成功时为布尔值,否则为错误代码数组。

标签: php oop methods return


【解决方案1】:

使用 try ... catch 语法。

例如:

try {
    $user->save();
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

http://php.net/manual/en/language.exceptions.php

【讨论】:

  • 所以在我的保存方法中,如果填充了错误消息数组,我会抛出异常吗?如何在异常中包含多个错误消息?所以我可以将它们展示给用户。
【解决方案2】:

如果save() 遇到任何问题,我会抛出异常。

如果您想提供一组验证错误,您可以继承 Exception 并提供一种存储验证错误的机制。

自定义 Exception 子类还可以帮助您区分代码显式抛出的异常(您希望捕获)和您没有预料到的异常(应该是致命的)。

这是子类:

class UserException extends Exception
{
    private $userMessages;

    public function __construct($message = "", $code = 0, Exception $previous = null, array $userMessages = null)
    {
        parent::__construct($message, $code, $previous);
        if ($userMessages === null) {
             $this->userMessages = array();
        } else {
            $this->userMessages = $userMessages;
        }
    }

    public function getUserMessages()
    {
        return $this->userMessages;
    }
}

这是 User 类的愚蠢版本,它总是在 save() 上引发异常。

class User
{
    public function save()
    {
        $userMessages = array(
            'Your password is wrong',
            'Your username is silly',
            'Your favorite color is ugly'
        );

        throw new UserException('User Errors', 0 , null, $userMessages);
    }
}

使用它:

$user = new User();

try {
    $user->save();
} catch (UserException $e) {
    foreach ($e->getUserMessages() as $message) {
        print $message . "\n";
    }
}

您还可以通过使用分号分隔的消息列表填充异常的 $message 来完成类似的操作。您甚至可以为错误类型构建一个常量列表,然后将它们组合为位掩码并将其用于异常的 $code。这些选项的优点是您将使用内置成员而不添加任何额外内容。

更多关于例外的信息: http://php.net/manual/en/language.exceptions.php

【讨论】:

    【解决方案3】:

    我在使用 erlang 玩了一段时间后养成的一个(坏的?)习惯是返回元组值(作为 php 数组)。

    function my_func() {
        $success = true;
        $errors = array();
        if ( something_fails() ) {
            $success = false;
            $errors[] = 'something failed..';
        }
        return array( $success, $errors );
    }
    
    list($success, $errors) = my_func();
    if ( ! $success ) {
        do_somthing_with( $errors );
    }
    

    根据我的经验,当出现狂野的modify legacy code 票证并且您真的不敢修改任何内容但可以更轻松地向其中添加更多legacy 时,这非常方便。

    干杯-

    【讨论】:

      【解决方案4】:

      返回 true 或错误数组。 当你检查它时,使用这个:

      if ($user->save()===true) {
          // display success to user
      } else {
          // display error to user
      }
      

      === 运算符执行类型安全比较,这意味着它不仅检查值是否为真,而且检查类型是否为布尔值。如果正在返回数组,则将其处理为 false。

      【讨论】:

        【解决方案5】:

        像这样从验证函数返回数组会很好

        $result['ACK'] = 'true';
        $result['message'] = 'Success validation'];
        

        失败

        $result['ACK'] = 'false';
        $result['message'] = 'validation error message';
        

        现在你可以像这样在前端使用这个数组

        if ($result['ACK']) {
            //No Error
        } else {
            echo $result['message'];
        }
        

        【讨论】:

          【解决方案6】:

          将您的条件更改为,如果为真则成功,否则返回错误数组。

          if ($user->save() === true) {
              //display success to user
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-12
            • 2021-04-03
            • 1970-01-01
            • 1970-01-01
            • 2020-10-13
            • 1970-01-01
            • 1970-01-01
            • 2017-05-17
            相关资源
            最近更新 更多