Find the URl causing your WordPress Error


PHP has some pretty good error handling and logging, but I do sometimes find it confusing. For example, look at this warning message:

[18-Oct-2023 12:34:56 UTC] PHP Warning: Something bad happened in /wp-content/something.php on line 123

OK, so we can go to something.php and scroll to line 123 and try to figure out what's gone wrong. But we don't know which page, post, or URl caused the error. If the error only occurs on /page/test?input=6 and not /page/test?output=7 that would be handy to know, right?

So here's some PHP you can stick in your theme's functions.php file:

PHP PHPfunction custom_warning_handler($errno, $errstr, $errfile, $errline) {
    $url = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] : 'Unknown URL';
    error_log("Warning at $url: [$errno] $errstr in $errfile on line $errline");
}
set_error_handler('custom_warning_handler', E_WARNING);

Now your error_log file will contain:

[18-Oct-2023 12:34:56 UTC] Warning at example.com/blog/page.php?foo=bar: [2] Cannot apply fuzz to kittens in /wp-content/something.php on line 123

You can find out more about set_error_handler() and how to configure it.


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

2 thoughts on “Find the URl causing your WordPress Error”

  1. Dave Cridland says:

    Of course, it's possible to get better error handling than a log file - I highly recommend Sentry for this kind of case. There's a free tier, or it's not-quite-open source if you can (and want to) run your own. It'll not only trap the error and give you a shiny stack trace and a report of when, how, and what logs ran up to the the error, but you can even record the screen of the user (sort of).

    On PHP, this uses that set_error_handler() mechanism of course, but also hooks into logging and more to give you a full picture.

    Reply
  2. says:

    I've also just manually cross-referenced the error_log with the access_log to get the full URL for simple cases. You might find it useful to also record the REQUEST_METHOD as sometimes the pages only fail on POST requests (I have seen strange errors before when working with REST systems where DELETE HTTP requests would cause errors due to poor implementations)

    Reply

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">