Converting errors to exceptions: design flaw?

后端 未结 3 1181
梦毁少年i
梦毁少年i 2021-01-02 06:05

I came across some code recently that used a custom error handler to turn any PHP errors into an generalized application exception. A custom exception handler was also defin

相关标签:
3条回答
  • 2021-01-02 06:08

    I convert everything, including notices to exceptions. There's no reason to allow exceptions to continue normally as it does. Undefined variable or offset? That's a problem.

    https://github.com/KyleWolfe/PHPErrorNet

    0 讨论(0)
  • 2021-01-02 06:11

    Personally, I do this all the time. The only difference is that in my error_handler function, I check to see if the error is an E_NOTICE first, and only throw if it is not (I log the notice anyway)...

    I would change the AppException to something that extends ErrorException... Something like: PhpRuntimeErrorException extends ErrorException which you ONLY use for PHP errors... The reason is so that it's more readable (it's easier to tell what a PhpRuntimeErrorException is without needing to figure out where it's thrown). The other reason, is that the ErrorException will store the generating line/file/etc information, where it would not be stored elsewhere (since the backtrace starts from the throw line)...

    So, then you can "try" code like this:

    try {
        $f = fopen('foo.bar', 'r');
        $ret = '';
        while ($data = fread($f)) {
            $ret .= process($data);
        }
        fclose($f);
        return '';
    } catch (PHPRuntimeErrorException $e) {
        throw new RuntimeException('Could not open file');
    } catch (ProcessException $e) {
        fclose($f);
        throw new RuntimeException('Could not process data');
    }
    return $ret;
    

    I also make my default exception handler generate a 500 server error page. That's because any exceptions should be caught, and if they were not, it really is a server error...

    Just my experience and opinion...

    0 讨论(0)
  • 2021-01-02 06:24

    There has been some debate about this in the PHP community. I believe the general thinking is that errors are things thrown by internal PHP functions, and are coding problems you really need to fix; whereas exceptions are things thrown by your application code that you may just need to 'handle'.

    However some of the newer SPL extensions (which tend to be more object oriented) do use exceptions for things previously might have thrown errors, so there is some grey area.

    There's also a PHP core class ErrorException - http://www.php.net/manual/en/class.errorexception.php which looks a little easier to use than your code example, if this is a route you want to go down.

    0 讨论(0)
提交回复
热议问题