1

Similar question has been asked few days ago about error handling. People explained to me how to get errors from class. And i understand it how to create error names and validate in __construct section but still struggling with multiple functions

    class magic
{
    /**
     * @param string $name
     * @param string $surname
     * @param int $age
     * @throws Exception
     */
    public function __construct($name, $surname, $age)
    {
        $errors = [];

        if (empty($name)) {
            $errors[] = 'Name is required.';
        }

        if (empty($surname)) {
            $errors[] = 'Surname is required.';
        }

        if (!empty($errors)) {
            throw new Exception(implode('<br />', $errors));
        }

        $this->name = $name;
        $this->surname = $surname;
        $this->age = $age;
    }

    public function printFullname()
    {
        echo $this->name . ' ' . $this->surname;
    }

}

another file:

include 'class.php'; 
    try {
        $test = new magic('', '', '33');
        $test->printFullname();
    } catch (Exception $exc) {
        echo $exc->getMessage(); //error messages
    }

It works but problem with another function in this class:

class magic
    {
        /**
         * @param string $name
         * @param string $surname
         * @param int $age
         * @throws Exception
         */
        public function __construct($name, $surname, $age)
        {
            $errors = [];

            if (empty($name)) {
                $errors[] = 'Name is required.';
            }

            if (empty($surname)) {
                $errors[] = 'Surname is required.';
            }

            if (!empty($errors)) {
                throw new Exception(implode('<br />', $errors));
            }

            $this->name = $name;
            $this->surname = $surname;
            $this->age = $age;
        }

        public function printFullname()
        {
            echo $this->name . ' ' . $this->surname;
        }

public function auth()
{
//authentication goes here

if... 
$errors[] = 'Error1';
else
$errors[] = 'Error2';
etc...

}


}

another file:

include 'class.php'; 
        try {
            $test = new magic('', '', '33');
            $test->auth();
        } catch (Exception $exc) {
            echo $exc->getMessage(); //error messages
        }

My function auth() working and return errors as if then echo but i would like to do with array.

5
  • When calling $test = new magic('', '', '33'); the constructor throws an exception and never returns an instantiated object. Therefore $test will be null and $test->auth(); is not executed at all. Exceptions are maybe not the best way to handle user input errors. Commented Jun 30, 2016 at 10:15
  • @feeela so you saying is better to have simple if then echo ''; in each function? Commented Jun 30, 2016 at 10:18
  • No, you can throw an InvalidArgumentException in the constructor if some required argument is not as expected. But a method like auth() should return status codes. Storing the error texts in the class itself is not the best idea, since you might want to present some useful error message to the client. If you return error codes you can then display a message in different languages and so on. But the idea to use typed exceptions (see answer of @GiamPy) would also work. Commented Jun 30, 2016 at 10:21
  • @feeela I lost completely now. Could you give to me some example because as i said before i'm beginner Commented Jun 30, 2016 at 10:28
  • i add throw new Exception('error name); instead echo and it works Commented Jun 30, 2016 at 10:40

2 Answers 2

2

I think what you are doing is unnecessary.

By the way you've written the constructor parameters, you are automatically saying that those parameters are required and must not be empty, since you haven't set a default value for them.

As for errors in multiple functions, I'd suggest you to look up at custom Exceptions. Create a custom Exception for every specific error (if you need to apply different actions or different types of errors) and then catch them as you would do with an Exception.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to get errors from the exception as an array you should create your own exception class:

class MagicException extends Exception
{
    private $errors;

    function __construct($message, array $errors, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
        $this->errors = $errors;
    }

    function getErrors()
    {
        return $this->errors;
    }
}

Usage:

try {
    $errors = [];

    // some code..
    $errors[] = 'Example error';

    if ($errors) {
        throw new MagicException('Something went wrong', $errors);
    }
} catch (MagicException $e) {
    // @todo: handle the exception
    print_r($e->getErrors());
}

Output:

Array
(
    [0] => Example error
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.