views:

862

answers:

4

I am using trigger_error to "throw" errors in a custom class. My problem is that trigger_error prints out the line number where trigger_error was called. For example, given the following code:

01    <?php
02        class Test {
03            function doAction() {
04                $this->doSubAction();
05            }
06            
07            function doSubAction() {
08                if(true)
09                    trigger_error('Custom error', E_USER_WARNING);
10            }
11        }
12        
13        $var = new Test();
14        $var->doAction();
15    ?>

PHP will print out the following:

Warning: Custom error in test.php on line 9

How would you make PHP return the line where the doAction() function was called (the method called outside the class, ignoring all calls made internally) as follows?

Warning: Custom error in test.php on line 14

Edit: Modified my example to be something a bit closer to what I'm trying to achieve.

+2  A: 

The best thing to do is set up an error handler that shows a full stack trace.

Set up a custom error handler, and call debug_print_backtrace() in it. You will find this useful in general, as well in this specific circumstance.

Jerub
A: 

Two options, neither one are particularly palatable:

  • Override Have test() provide __LINE__ in the arguments (eg. "test(__LINE__)", and give the argument to trigger_error). Set an error handler to print a custom error message. NOTE: This is horrifically ugly. :-)

  • Set up an error handler, and have it call and process the horrifically-large output of debug_backtrace(). This function can be useful when debugging... But is overkill for what you're trying to do. Please don't use this function as part of the regular operation of a system.

Short answer: too hard, don't try. :-|

Rob Howard
Presumably, the need for a line number would indicate a *really bad* error of some kind, one in which the developer would be required to do some serious debugging. In that case, I wouldn't have thought the overhead of parsing debug_backtrace()'s output WOULD be overkill.
Bobby Jack
A: 

I usually put a trigger_error() there also. This ensure that I know exactly where it's called and exactly where the actual error occured. I then send all of the errors to myself in an email when in production. I know this isn't automatic, but at least you can trace what happened.

Darryl Hein
A: 

Alright, for those of you who are interested in my final solution, I integrated the following piece of code in our framework which returns the correct line number in all the cases that we could of tested. We are using it in production.

ErrorHandler class

It catches uncaught PHP exceptions, PHP errors and PEAR::Error s. You will need to modify it a bit has the code has some framework specific functions, but they shouldn't be to hard to track down. Enjoy!

Andrew Moore