How to handle an exception in another catch try block?

My example:

class CustomException extends \Exception {

}

class FirstClass {
    function method() {
        try {
            $get = external();
            if (!isset($get['ok'])) {
                throw new CustomException;
            }

            return $get;
        } catch (Exception $ex) {
            echo 'ERROR1'; die();
        }
    }
}

class SecondClass {
    function get() {
        try {
            $firstClass = new FirstClass();
            $get = $firstClass->method();
        } catch (CustomException $e) {
            echo 'ERROR2'; die();
        }
    }
}

$secondClass = new SecondClass();
$secondClass->get();

This will return me “ERROR1”, but I would like to get “ERROR2” from SecondClass.

In the FirstClass block, try catch should handle errors from the external () method.

How can i do this?

+4
source share
1 answer

Instead of printing an error message and dying the whole php process, you should rather throw another exception and register a global exception handler that handles the exception for unhandled exceptions.

class CustomException extends \Exception {

}

class FirstClass {
    function method() {
        try {
            $get = external();
            if (!isset($get['ok'])) {
                throw new CustomException;
            }

            return $get;
        } catch (Exception $ex) {
            // maybe do some cleanups..
            throw $ex;
        }
    }
}

class SecondClass {
    function get() {
        try {
            $firstClass = new FirstClass();
            $get = $firstClass->method();
        } catch (CustomException $e) {
            // some other cleanups
            throw $e;
        }
    }
}

$secondClass = new SecondClass();
$secondClass->get();

You can register a global exception handler with set_exception_handler

set_exception_handler(function ($exception) {
    echo "Uncaught exception: " , $exception->getMessage(), "\n";
});
0
source

Source: https://habr.com/ru/post/1687555/


All Articles