Treating Warnings as Errors

ぃ、小莉子 提交于 2019-12-21 03:37:25

问题


I have a php application that I have just re-factored. Unfortunately it spewing out warnings like:

Warning: preg_match() expects parameter 2 to be string, object given in /home/yacoby/dev/netbeans/php/Zend/Db/Select.php on line 776

Which is impossible (or very hard work) to work out the issue as I don't have a callstack so can't tell which parts of my code are causing the warning and there is a lot of code.

I need a method to either treat warnings like errors (In that the application dies and prints the stacktrace) or I need the stacktrace to be shown when printing errors. Is there a method to do this?


回答1:


See example #1 at http://www.php.net/manual/en/class.errorexception.php

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>



回答2:


Have a look at set_error_handler() and include this at the beginning of your scripts or in your bootstrap to just print the stacktrace when E_WARNINGs occur.

function stacktrace_error_handler($errno,$message,$file,$line,$context)
{
    if($errno === E_WARNING) {
        debug_print_backtrace();
    }
    return false; // to execute the regular error handler
}
set_error_handler("stacktrace_error_handler");

For more control over the various types, have a look at the more explicit version posted elsewhere in the answers.




回答3:


You can define your own error handler using set_error_handler()

In the handler function you can treat each class of error however you want. Here's a basic template that I use, in my case I only want to handle fatal errors, so I ignore notices and warnings.

In your case you could do a backtrace on warnings, or log them however you want

function error_handler($errno,$message,$file,$line,$context) {

switch($errno) {
    // ignore warnings and notices
    case E_WARNING:
    case E_NOTICE:
    case E_USER_NOTICE:
    case E_USER_WARNING:
        break;
    // log PHP and user errors
    case E_ERROR:
    case E_USER_ERROR:
              // Do some processing on fatal errors
    }
}


来源:https://stackoverflow.com/questions/2071024/treating-warnings-as-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!