开发者

PHP Exception handler kills script

basically i have a custom exception handler. When i handle an exception, i just want it to echo the message and continue the script. But after my method handles the exception, the script doesnt continue.

开发者_StackOverflow

Is this a behaviour of php or is my exception handler doing something wrong?


This is a behavior of php. This differs from set_error_handler() in that, according to the manual on set_exception_handler(), Execution will stop after the exception_handler is called. Therefore, ensure you catch all exceptions, letting only those you want to kill your script through.

This is actually why set_error_handler() doesn't pair well with exceptions and set_exception_handler() when converting all errors to exceptions... unless you actually mean your application to be so strictly coded that any notice or warning halts the script. But at least it gives you a trace on that call involving an unset array key.


With a custom exception handler, you'll want to catch the exception in a try/catch block and do whatever handling you want in there.

The following is the example from The CodeUnit of Craig

try {
    $error = 'Throw this error';
    throw new Exception($error);
    echo 'Never get here';
}
catch (Exception $e)
{
    echo 'Exception caught: ',  $e->getMessage(), "\n";
}

If you want to catch and print any unhandled exception, you can set a top level exception handler like this example from w3schools(near the bottom of the page)

<?php
 function myException($exception){
    echo "<b>Exception:</b> " , $exception->getMessage();
 }

 set_exception_handler('myException');

 throw new Exception('Uncaught Exception occurred');
?> 

should print: "Exception: Uncaught Exception occurred"


Look at the following code. it worked for me:

define(BR, "<br/>");
try {
   echo "throwing exception" . BR;
   throw new Exception("This is exception");
}
catch(Exception $ex) {
    echo "caught exception: " . BR . $ex->getMessage() . BR;

}
echo "Keep on going!. ..." . BR;

it prints the following:

throwing exception
caught exception: 
This is exception
Keep on going!. ...

What do you say ? Can you show the code of your code handler ?


You could do this :

function handleError($errno, $errstring, $errfile, $errline, $errcontext) {
    if (error_reporting() & $errno) {
        // only process when included in error_reporting
        return processError($errno, $errstring);
    }
    return true;
}

function handleException($exception){
    // Here, you do whatever you want with the generated
    // exceptions. You can store them in a file or database,
    // output them in a debug section of your page or do
    // pretty much anything else with it, as if it's a
    // normal variable
}

function processError($code, $message){
    switch ($code) {
        case E_ERROR:
        case E_CORE_ERROR:
        case E_USER_ERROR:
            // Throw exception and stop execution of script
            throw new Exception($message, $code);
        default:
            // Execute exception handler and continue execution afterwards
            return handleException(new Exception($message, $code));
    }
}

// Set error handler to your custom handler
set_error_handler('handleError');
// Set exception handler to your custom handler
set_exception_handler('handleException');


// ---------------------------------- //

// Generate warning
processError(E_USER_WARNING, 'This went wrong, but we can continue');

// Generate fatal error :
processError(E_USER_ERROR, 'This went horrible wrong');

Alternate approach :

function handleError($errno, $errstring, $errfile, $errline, $errcontext) {
    if (error_reporting() & $errno) {
        // only process when included in error_reporting
        return handleException(new \Exception($errstring, $errno));
    }
    return true;
}

function handleException($exception){
    // Here, you do whatever you want with the generated
    // exceptions. You can store them in a file or database,
    // output them in a debug section of your page or do
    // pretty much anything else with it, as if it's a
    // normal variable

    switch ($code) {
        case E_ERROR:
        case E_CORE_ERROR:
        case E_USER_ERROR:
            // Make sure script exits here
            exit(1);
        default:
            // Let script continue
            return true;
    }
}

// Set error handler to your custom handler
set_error_handler('handleError');
// Set exception handler to your custom handler
set_exception_handler('handleException');


// ---------------------------------- //

// Generate warning
trigger_error('This went wrong, but we can continue', E_USER_WARNING);

// Generate fatal error :
trigger_error('This went horrible wrong', E_USER_ERROR);

An advantage of the latter strategy, is that you get the $errcontext parameter if you do $exception->getTrace() within the function handleException.

This is very useful for certain debugging purposes. Unfortunately, this works only if you use trigger_error directly from your context, which means you can't use a wrapper function/method to alias the trigger_error function (so you can't do something like function debug($code, $message) { return trigger_error($message, $code); } if you want the context data in your trace).


EDIT

I've found one dirty workaround for the trigger_error problem.

Consider the following code :

define("__DEBUG__", "Use of undefined constant DEBUG - assumed 'DEBUG'");

public static function handleError($code, $message, $file, $line, $context = false) {
    if ($message == __DEBUG__) {
        return static::exception(new \Exception(__DEBUG__, E_USER_WARNING));
    } else {
        if (error_reporting() & $code) {
            return static::exception(new \Exception($message, $code));
        }
        return true;
    }
}

public static function handleException($e) {
    global $debug;
    $code = $e->getCode();
    $trace = $e->getTrace();
    if ($e->getMessage() == __DEBUG__) {
        // DEBUG
        array_push($debug, array(
            '__TIME__' => microtime(),
            '__CONTEXT__' => array(
                'file' => $trace[0]['file'],
                'line' => $trace[0]['line'],
                'function' => $trace[1]['function'],
                'class' => $trace[1]['class'],
                'type' => $trace[1]['type'],
                'args' => $trace[0]['args'][4]
            )
        ));
    } else {
       // NORMAL ERROR HANDLING
    }
    return true;
}

With this code, you can use the statement DEBUG; to generate a list of all available variables and a stack trace for any specific context. This list is stored in the global variable $debug. You can add it to a log file, add it to a database or print it out.

This is a VERY, VERY dirty hack, though, so use it at your own discretion. However, it can make debugging a lot easier and allows you to create a clean UI for your debug code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜