A
A
Alexander2016-08-12 21:16:39
PHP
Alexander, 2016-08-12 21:16:39

Do I need to throw an exception when receiving erroneous (invalid) data?

Do I need to throw an exception in cases where the data did not pass validation? Or is it enough just to put the code and the error message into the errors array and work with it when outputting?
UPD. To be clear: I only want to use exceptions to log traces to a file. Is the information from Validation Exceptions useful during debugging?
UPD2. Understood. Discussed following. logic:
Working with erroneous data can cause an error directly during their processing. For example, an attempt to watermark a received file will cause an error if another type of file was received (**.exe, .*psd, etc.)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Muhammad, 2016-08-12
@websiteserf

Yes, you do, in most cases. You can create a ValidationException class that takes an array of error messages in the constructor and inherit it from the Exception class:

class ValidationException extends Exception
{
    /**
     * Validation error messages.
     * 
     * @var array
     */
    protected $errors = [];

    /**
     * Constructor.
     * 
     * @param array $errors
     */
    public function __construct($errors)
    {
        $this -> errors = $errors;
    }

    /* геттер для свойства $errors */
}

R
Roman, 2016-08-12
@r_zaycev

An exception is thrown in an exceptional situation that cannot be prevented. Validation of received data is clearly not the case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question