-
The <o:scriptErrorHandler> is a component that catches uncaught JavaScript errors and unhandled promise rejections on the client and sends them to the server via navigator.sendBeacon(), where they are fired as ScriptError CDI events. This allows server-side logging of client-side JavaScript errors without any additional endpoint boilerplate.
Usage (client)
Just put the component in the <h:head> of the master template. It will automatically move itself to head even when placed elsewhere, but placing it in <h:head> makes the intent explicit.
<h:head>
<o:scriptErrorHandler />
</h:head>
This will register window.onerror and unhandledrejection event listeners which report any uncaught client-side errors to the server. You can optionally specify a CSS selector via ignoreSelector to suppress error reporting when a matching element exists in the document (e.g. on error pages where errors are expected).
<o:scriptErrorHandler ignoreSelector="body.errorPage" />
Usage (server)
Create a CDI bean (typically application scoped) that observes the ScriptError event.
@ApplicationScoped
public class ScriptErrorObserver {
private static final Logger logger = Logger.getLogger(ScriptErrorObserver.class.getName());
public void onScriptError(@Observes ScriptError error) {
logger.warning(error.toString());
}
}
The ScriptError event provides the following information:
ScriptError.pageURL(): the URL of the page where the error occurred.ScriptError.errorMessage(): the error message.ScriptError.errorName(): the error type (e.g. "TypeError", "ReferenceError").ScriptError.errorStack(): the full stack trace.ScriptError.sourceURL(): the URL of the script file where the error occurred.ScriptError.lineNumber(): the line number in the script.ScriptError.columnNumber(): the column number in the script.ScriptError.remoteAddr(): the remote address.ScriptError.userAgent(): the User-Agent header.ScriptError.userPrincipal(): the authenticated user principal name.
Deduplication
To prevent flooding the server with repeated errors (e.g. from a requestAnimationFrame loop), the client-side script deduplicates errors by message, source URL, and line number. The deduplication queue size and expiry time can be configured via the maxRecentErrors and errorExpiry attributes, which default to 100 and 1 minute respectively.
VDL documentation
API documentation
Java source code
org.omnifaces.servlet.ScriptErrorServletorg.omnifaces.component.script.ScriptErrorHandlerorg.omnifaces.cdi.ScriptError