Question

I have a php file that is only accessed through ajax. The ajax call expects only data formatted as a json_encoded output. I am trying to make a custom error handler function that catches php errors, and rather than outputting them directly, instead passes them to the array they is encoded for the json parser.

So far I have

// error handler function
function handleErrors($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    $response['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";

    /* Don't execute PHP internal error handler */
    return true;
}

set_error_handler("handleErrors");

//do other stuff that might trigger php errors

if ($result===true){
    $response['success'] = true;
}else{
    $response['success'] = false;
    $response['error'] = $result;
    $response['request'] = json_encode($_REQUEST);
}

echo json_encode($response);

My issue is that the $response array is out of scope for the rest of the document to access so that it will be output in the json object. Is there some way of passing a variable by reference into the custom function or another way I have overlooked?

Was it helpful?

Solution

In a OOP context you can define $response as a property.

class myclass {

    var $response;

    function __construct()
    {
        set_error_handler(array($this, 'handleErrors'));
    }

    function handleErrors($errno, $errstr, $errfile, $errline)
    {
        if ( ! (error_reporting() & $errno))
        {
            // This error code is not included in error_reporting
            return;
        }

        $this->response['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";

        /* Don't execute PHP internal error handler */
        return true;
    }

    function outputAjax()
    {
        // my code

        if ($result === true)
        {
            $this->response['success'] = true;
        } else
        {
            $this->response['success'] = false;
            $this->response['error'] = $result;
            $this->response['request'] = json_encode($_REQUEST);
        }

        echo json_encode($this->response);
    }

}

OTHER TIPS

Define $response as global in you function

function handleErrors($errno, $errstr, $errfile, $errline)
{
    global $response;
    //further code..
}

OR use $GLOBALS

$GLOBALS['response']['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top