John Davidson

php - Variable/Dynamic Exception Type in Catch Block

0 comments
Message:


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.



My Answer:
type as arguments. The function should then try to execute the callable and catch any exceptions of the specified type. If an exception of the specified type is caught, the function should return the exception message. If no exception of the specified type is caught, the function should return null.

Here is an example implementation of this function:

php
function tryCatch($callable, $exceptionType) {
try {
$callable();
} catch (\Exception $e) {
if ($e instanceof $exceptionType) {
return $e->getMessage();
}
}
return null;
}

// Example usage
function testFunction() {
throw new \InvalidArgumentException('Invalid argument');
}

$result = tryCatch('testFunction', \InvalidArgumentException::class);
echo $result; // Output: Invalid argument

$result = tryCatch('testFunction', \RuntimeException::class);
echo $result; // Output: null


In this implementation, the `tryCatch` function takes a callable and an exception type as arguments. It then tries to execute the callable and catches any exceptions that are thrown. If the caught exception is an instance of the specified exception type, the function returns the exception message. Otherwise, it returns null.

You can use this function to easily handle different types of exceptions in your code and take appropriate actions based on the caught exception type.

Rate this post

3 of 5 based on 5637 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us