Home > Software design >  Variable/Dynamic Exception Type in Catch Block
Variable/Dynamic Exception Type in Catch Block

Time:02-05

I am trying to create a function that when called is passed a callable and an exception "type", either as a ::class string or something like that. The idea would be that the function would call the callback inside of a try/catch block.

Sample Function:

public static function try(callable $callback, string $exceptionClass) : object | null {
     try {
         ...
         $callback();
         ...
     catch($exceptionClass $e) {
         ...
     }
}

I found this answer. But I'm not sure how to get the type.

CodePudding user response:

You can't use a variable in the catch like this:

try {
    $callback();
} catch ($exceptionClass $e) {
}

You'll have to do something like this, where you catch everything, and then conditionally check the exception type:

try {
    $callback();
} catch (\Throwable $e) {
    if ($e instanceof $exceptionClass) {
    }
}
  •  Tags:  
  • Related