开发者

What is the standard way to return errors to the user from a function?

What is the standard way to return errors to the user from a function? (email invalid, max characters exeeded, etc.)

function register($name, $email) {
     if(!$name) {
            $registra开发者_如何学Pythontion_errors = 'name empty,';
     }

     if(!email) {
            $registration_errors = $errors . 'email empty,';
     }

     if($registration_errors) {
           return $registration_errors;
     }
     else {
         register stuff........
         return true;
     }
}

now the problem is that it always returns true so you cant do something like:

if(register()) {blah blah blah} else { put errors under inputs}

So what would be the standard method of doing this?


use something like this

function register
{
.. 
else
{
return array('error' => $errorwhichyoufound);
}
....
}
$result = register();
if((array_key_exists('error', $result)))
{

}
else
{
}

This way you can even check for individual errors.


<?php
// in your register function:
$registration_errors = array();
if (!$name) {
    $registration_errors['name'] = 'Name is required.';
}
// etc.
?>

<!-- in your phtml: -->
<?php if (array_key_exists('name', $registration_errors) echo $registration_errors['name'];?>
<label for="name">Name</label>
<input id="name" name="name" type="text" value="<?php echo $name; ?>" />


There are all sorts of ways to do this, and you might even consider some of them "standard". You could return an array containing the error code (as the answers above), you could store the error as an object property (requiring you to call "register" as an object method), you could store the error in a global variable, or put the error in a registered location. You could pass in a variable reference and set the variable value to the error. You could reverse the return logic, so a string would be false and a zero would be a true value. You could raise an error. You could throw an exception.

The real problem here is that the "register" function is supposed to perform some function and you are asking it to sanitize the input just in case something funny is going on. So if you really need to sanitize $name and $email, why not do that validation before the call to register? You are going to need some kind of error path regardless, and perhaps several different error messages depending on the situation. When you are finally ready to call register, it should succeed or fail for its own reasons, and not because the business rules require a non-empty email address.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜