V
V
vitaly_742021-09-13 10:58:55
PHP
vitaly_74, 2021-09-13 10:58:55

Is it possible to organize a centralized error management in this case?

Hello, I have an interface like this:

interface Entities extends \Iterator
{
    /**
     * @return Entity[]
    */
    public function list(): array;

    /**
     * @param Form $form - форма, которая выдает провалидированные данные
     * @return Entity - Проблема которую нужно решить
     */
    public function addFromInput(Form $form): Entity;
}


the question is if I throw an exception in the addFrimInput($form) method. then is it possible to somehow write some kind of wrapper or common place for exception handling?
My problem is that the method must return something and not just something, but an entity.
there was an idea to throw out NullObject,
but if I throw out an error at a lower level (a form validation error, for example), then you won’t get NullObject here. because the error has nothing to do with the object.
try{
//программа работает нормально
}
catch(Exception){
//тут должен вернуть сущность Entity
}

Exception handling in actions - I do not consider it because of the strong binding to the framework. I would like to do everything in my objects.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ichi Nya, 2021-09-23
@vitaly_74

You can also catch separately defined exceptions, there is also a finally block that will be executed anyway.

try {
    // код
} catch (ICreateNewException $e) {
    echo 'Сработало исключения создания: ',  $e->getMessage(), "\n";
} catch (Exception $e) {
    echo 'Поймано исключение: ',  $e->getMessage(), "\n";
} finally {
    echo "Это я выполню всё равно";
}

in order not to write like this every time, you can create a function into which to pass the callback function
// это примерный код просто для визуального примера
function ($callback, $args,$default)
{
try {
  $r = $callback($args);
// or call_user_func(array($callback, $args))
} catch (ICreateNewException $e) {
    echo 'Сработало исключения создания: ',  $e->getMessage(), "\n";
return new NullObj;
} catch (Exception $e) {
    echo 'Поймано исключение: ',  $e->getMessage(), "\n";
mail(config('mail.to'))
} finally {
    return $default;
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question