1

I have a file with all my custom exceptions:

class InvalidEmailException extends Exception {
    public function errorMessage() {
        return 'Please enter a valid email address';
    }
}

class ExistingEmailException extends Exception {
    public function errorMessage() {
        return 'An account with this email address already exists';
    }
}

// More...

And every time I want to show the error of one I must use:

try {
    // Code with several possible exceptions...
} catch (\InvalidEmailException $th) {
    $responser->showError($th->errorMessage());
} catch (\ExistingEmailException $th) {
    $responser->showError($th->errorMessage());
} // More...

What I want is to create an interface or something similar that allows me to call the errorMessage() method of the required exception without indicating each and every one of them separately. Something like this:

catch (\ExceptionManager $th) { // All-in-One
    $responser->showError($th->errorMessage());
}

I do not know if I have explained myself and not if it is possible, but I have tried it with an interface and obviously PHP asks me to add all methods of the Exception class to each one. Thanks!

Brahim
  • 21
  • 1

1 Answers1

0

You can use

try {
    // Code with several possible exceptions...
} catch (\Exception $ex) {
    $responser->showError($ex->getMessage());
} 

Or if you are using PHP 7 or greater:

try {
    // Code with several possible exceptions...
} catch (\Trowable $th) {
    $responser->showError($th->getMessage());
} 

Notice, the $th->getMessage() method instead of $th->errorMessage() Also, let's be aware that exception and error in PHP are two different things.

  • \Exception will catch exceptions.
  • \Error will catch error exceptions
  • Throwable will catch both.

You can support PHP 5 and 7 by combining the two:

try {
    // Code with several possible exceptions...
} catch (\Exception $ex) {
    $responser->showError($ex->getMessage());
} catch (\Trowable $th) {
    $responser->showError($th->getMessage());
} 
Prince Dorcis
  • 955
  • 7
  • 7