Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying PHP Errors from admin-ajax.php in Wordpress 4.9+

We've got some custom endpoints set up that do various things, which we access via /wp/wp-admin/admin-ajax.php?action=some_action

However whenever there is an error as we're developing, such as syntax, logical, fatal etc, we simply get "500 Internal Server Error" when viewing the page in the browser.

Every other page on the site when there's an error, it gives us the PHP error, to help us debug.

However when the error comes from the admin-ajax.php area, we have to then open our PHP Log file to see the error instead - which is more of a pain when actively developing

Is there something in wordpress that disables displaying of errors on this URL namespace? and if so, how can we prevent this to allow rendering of the errors on the browser?

like image 353
owenmelbz Avatar asked Mar 26 '18 10:03

owenmelbz


2 Answers

Better Solution

Enable PHP Error Output before the error is occurring

Add this to enable PHP Error Output

@ini_set( 'display_errors', 1 );

Eg: At the start of the ajax callback function in this case

Tip:

You can use the Preview tab next to the Response tab in the Dev Tools Network to render the HTML in the Error output. So that you can see the Error without the HTML

Image

Explanation

I don't know why WordPress does not allow enabling this error output but I don't think editing the WordPress Core file and undoing them after debugging is not a good idea as answered here

From that answer, I found that we just need to set the display_errors PHP init setting to true or 1 in order to output the errors.

So why don't we just set this wherever we want this to work so that this display_errors will be enabled for that scop only.

There is no problem if you didn't undo this unlike the other answer

like image 124
ABHi Avatar answered Sep 16 '22 15:09

ABHi


enter image description hereIf you want to see the PHP errors when using ajax, open up the wp-includes/load.php file & on line 336, change this line:

if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
        @ini_set( 'display_errors', 0 );
    }

to

if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
        @ini_set( 'display_errors', 1 );
    }

You will now be able to see the ajax errors in your browser console. Remember to undo this when finished debugging!

like image 38
kb. Avatar answered Sep 20 '22 15:09

kb.