Handle JavaScript errors: try/catch, Promise rejections and window.onerror
One uncaught error in a theme script can stop everything after it: the menu does not open, the form does not send, and nobody notices, because the error appears only in the console of the visitor’s browser. Good error handling has two parts: catching expected errors where they happen, and collecting the unexpected ones from production.
Problem: Front-end features of a WordPress site sometimes stop working for some visitors, and the errors are never seen because they happen only in their browsers.
Solution: Wrap code that can fail for known reasons (parsing, network requests, third-party APIs) in try/catch with a fallback, handle rejected Promises, and report everything else with window.addEventListener( 'error' ) and 'unhandledrejection' to a small REST endpoint.
Expected errors
function readSettings( raw ) {
try {
return JSON.parse( raw );
} catch ( error ) {
console.warn( 'Invalid settings, using defaults', error );
return { perPage: 10 };
}
}
async function loadPosts( page ) {
try {
const response = await fetch( '/wp-json/wp/v2/posts?page=' + page );
if ( ! response.ok ) {
throw new Error( 'HTTP ' + response.status );
}
return await response.json();
} catch ( error ) {
showMessage( 'Posts could not be loaded. Please try again.' );
return [];
}
}
Catch errors where you can do something useful: show a message, use a default, retry. A catch that only logs and continues as if nothing happened often just moves the problem to the next line.
Keep one feature from breaking the others
Scripts of a theme are often one file that initialises several features. An error in the first one stops the rest:
[ initMenu, initSlider, initNewsletterForm ].forEach( function ( init ) {
try {
init();
} catch ( error ) {
reportError( error );
}
} );
Unexpected errors
function reportError( error, extra ) {
var data = {
message: String( error && error.message || error ),
stack: error && error.stack ? String( error.stack ).slice( 0, 2000 ) : '',
url: location.href,
extra: extra || ''
};
// sendBeacon survives page unloads and does not block anything
if ( navigator.sendBeacon ) {
navigator.sendBeacon( '/wp-json/ha/v1/js-error', new Blob( [ JSON.stringify( data ) ], { type: 'application/json' } ) );
}
}
window.addEventListener( 'error', function ( event ) {
reportError( event.error || event.message, event.filename + ':' + event.lineno );
} );
window.addEventListener( 'unhandledrejection', function ( event ) {
reportError( event.reason, 'unhandled promise rejection' );
} );
Errors in scripts from other domains (a CDN, an analytics service) arrive as “Script error.” without details, unless the script is loaded with crossorigin and the server allows it.
The endpoint
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'ha/v1', '/js-error', array(
'methods' => 'POST',
'permission_callback' => '__return_true',
'callback' => function ( WP_REST_Request $request ) {
$data = $request->get_json_params();
error_log( sprintf(
'JS error: %s | %s | %s',
sanitize_text_field( $data['message'] ?? '' ),
esc_url_raw( $data['url'] ?? '' ),
sanitize_text_field( $data['extra'] ?? '' )
) );
return new WP_REST_Response( null, 204 );
},
) );
} );
The endpoint is public, so it only writes short, sanitised lines to the PHP error log. On a busy site add a rate limit (for example a transient per IP), or use an error tracking service such as Sentry instead of your own log.
NOTE: Error reports often contain URLs with query strings and sometimes text the user typed. Do not log form contents, and treat the log as personal data: keep it short and delete old entries.