Good error handling with file_get_contents

后端 未结 5 1651
梦如初夏
梦如初夏 2020-11-30 10:26

I am making use of simplehtmldom which has this funciton:

// get html dom form file
function file_get_html() {
    $dom = new simple_html_dom;
    $args = fu         


        
5条回答
  •  野性不改
    2020-11-30 10:39

    From my POV, good error handling is one of the big challenges in PHP. Fortunately you can register your own Error Handler and decide for yourself what to do.

    You can define a fairly simple error handler like this:

    function throwExceptionOnError(int $errorCode , string $errorMessage) {
        // Usually you would check if the error code is serious
        // enough (like E_WARNING or E_ERROR) to throw an exception
        throw new Exception($errorMessage);
    }
    

    and register it in your function like so:

    function file_get_html() {
        $dom = new simple_html_dom;
        $args = func_get_args();
        set_error_handler("throwExceptionOnError");
        $dom->load(call_user_func_array('file_get_contents', $args), true);
        restore_error_handler();
        return $dom;
    }
    
    • For an exhaustive list of error codes see http://php.net/manual/errorfunc.constants.php
    • For a complete documentation of set_error_handler, see http://php.net/manual/en/function.set-error-handler.php

提交回复
热议问题