M
M
Max Ba2020-05-25 14:57:47
PHP
Max Ba, 2020-05-25 14:57:47

How to deal with multiple exceptions?

There are two classes. Both throw an exception if something went wrong.
Do I need to wrap each class, or both under each other in one tru cach condition?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Fedorov, 2020-05-25
@phpcoder81

It all depends on whether both classes together are part of the same layer or if it is an interaction between different layers.
In the first case, exceptions can be combined with a single interface (or parent exception). And on this generalized exception to be tied in another layer.

Example

class FirstException extend ModuleException {}
class SecondException extend ModuleException {}

class ModuleFirst 
{
     public function work()
     {
          throw new FirstException('first);
     }
}
class ModuleSecond 
{
     public function work()
     {
          throw new SecondException('second);
     }
}

тогда дальше ловить из слоя можно так
try {
    $module->work();
} catch(ModuleException $e) {
     // обработка
}


If the interaction between the layers, then wrap each time and throw yours further.
Example

class FirstException {}
class SecondException {}

class ModuleFirst 
{
     public function work()
     {
         try {
            $module2->work();
        } catch(SecondException $e) {
             throw new FirstException($e->getMessage, 0, $e);
        }
     }
}

class ModuleSecond 
{
     public function work()
     {
          throw new SecondException('second);
     }
}

try {
     $module1->work();
} catch(FirstException $e) {
    // обработка
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question