Specify page/line when throwing die()?
Question
I am using PHP 4, the only way I know of to cause an error and stop everything is calling die(). But in case I run into the error later and don't remember where its coming from I would like to specify the page and line number that the die() occurred on (like other php errors do). Is there a way to do this?
Thanks!
Solution
You should look into the magic constants.
echo __LINE__; // Line number
You can also run error_log() to send errors quietly to the log.
OTHER TIPS
I think you should use trigger_error() to generate an E_USER_ERROR or E_USER_WARNING. This allows you to control the behaviour in detail. For example you can specify whether the messages should be shown at all using error_reporting(), or handle the E_USER_WARNING:s explicitly using set_error_handler().
The simplest way is to use:
echo __FILE__ . ": line " . __LINE__;
die();
If you were to use PHP5, you could also use Exceptions:
throw new Exception("My error message!");
The stack trace will reveal the whole call stack and the line this was thrown on.
(EDIT: Thanks to [@John Isaacs] and [@Emil H] for informing me that Exceptions weren't added to PHP until PHP5)
In addition to @Jukka Dahlbom and @Ólafur Waage's suggestions you might also consider using debug_backtrace()
.
Better use error_log()
to report an error and debug_backtrace()
for debugging. You could also write your own error handling function (see set_error_handler()
) to combine both.