3

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

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

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

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

4

6 回答 6

9

使用try ... catch语法。

例如:

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

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

于 2013-09-24T11:11:23.480 回答
4

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

于 2013-09-24T13:52:13.000 回答
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

干杯 -

于 2013-09-24T12:03:03.517 回答
1

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

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

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

于 2013-09-24T11:12:07.343 回答
0

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

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

失败时

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

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

if ($result['ACK']) {
    //No Error
} else {
    echo $result['message'];
}
于 2013-09-24T11:11:35.867 回答
0

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

if ($user->save() === true) {
    //display success to user
}
于 2013-09-24T11:11:45.187 回答