- All Implemented Interfaces:
PartialStateHolder,StateHolder,TransientStateHolder,ComponentSystemEventListener,FacesListener,SystemEventListenerHolder,EventListener
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.
- Since:
- 5.2
- Author:
- Bauke Scholtz
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe component type, which is "org.omnifaces.component.script.ScriptErrorHandler".Fields inherited from class org.omnifaces.component.script.ScriptFamily
COMPONENT_FAMILYFields inherited from class jakarta.faces.component.UIComponent
ATTRS_WITH_DECLARED_DEFAULT_VALUES, BEANINFO_KEY, bindings, COMPOSITE_COMPONENT_TYPE_KEY, COMPOSITE_FACET_NAME, FACETS_KEY, VIEW_LOCATION_KEY -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidencodeChildren(FacesContext context) Render the initialization script.intReturns the time in milliseconds after which a recent error entry expires.Returns the CSS selector for elements whose presence suppresses error reporting.intReturns the maximum number of recent errors to keep for deduplication.voidprocessEvent(ComponentSystemEvent event) Move this component to head, so that error handlers are registered as early as possible.static voidregisterServletIfNecessary(ServletContext servletContext) Register the script error handler servlet if it has not already been registered and there is at least one CDI observer forScriptError.voidsetErrorExpiry(int errorExpiry) Sets the time in milliseconds after which a recent error entry expires for deduplication.voidsetIgnoreSelector(String ignoreSelector) Sets the CSS selector for elements whose presence suppresses error reporting.voidsetMaxRecentErrors(int maxRecentErrors) Sets the maximum number of recent errors to keep for deduplication.Methods inherited from class org.omnifaces.component.script.ScriptFamily
encodeBegin, encodeEnd, getFamily, getRendersChildren, moveToBodyMethods inherited from class jakarta.faces.component.UIComponentBase
addClientBehavior, addFacesListener, broadcast, clearInitialState, decode, encodeAll, findComponent, getAttributes, getChildCount, getChildren, getClientBehaviors, getClientId, getDefaultEventName, getEventNames, getFacesContext, getFacesListeners, getFacet, getFacetCount, getFacets, getFacetsAndChildren, getId, getParent, getPassThroughAttributes, getRenderer, getRendererType, invokeOnComponent, isRendered, isTransient, markInitialState, processDecodes, processRestoreState, processSaveState, processUpdates, processValidators, queueEvent, removeFacesListener, restoreAttachedState, restoreState, saveAttachedState, saveState, setId, setParent, setRendered, setRendererType, setTransient, visitTreeMethods inherited from class jakarta.faces.component.UIComponent
getClientId, getCompositeComponentParent, getContainerClientId, getCurrentComponent, getCurrentCompositeComponent, getListenersForEventClass, getNamingContainer, getPassThroughAttributes, getResourceBundleMap, getStateHelper, getStateHelper, getTransientStateHelper, getTransientStateHelper, getValueExpression, initialStateMarked, isCompositeComponent, isInView, isVisitable, popComponentFromEL, pushComponentToEL, restoreTransientState, saveTransientState, setInView, setValueExpression, subscribeToEvent, unsubscribeFromEvent
-
Field Details
-
COMPONENT_TYPE
The component type, which is "org.omnifaces.component.script.ScriptErrorHandler".- See Also:
-
-
Constructor Details
-
ScriptErrorHandler
public ScriptErrorHandler()
-
-
Method Details
-
processEvent
Move this component to head, so that error handlers are registered as early as possible.- Specified by:
processEventin interfaceComponentSystemEventListener- Overrides:
processEventin classUIComponent- Throws:
IllegalArgumentException- When theScriptErrorServletis not registered because no CDI observer forScriptErrorwas found.
-
encodeChildren
Render the initialization script.- Overrides:
encodeChildrenin classUIComponentBase- Throws:
IOException
-
getIgnoreSelector
Returns the CSS selector for elements whose presence suppresses error reporting. When an element matching this selector exists in the document, errors will not be sent to the server. For example,body.errorPageto suppress reporting on error pages having<h:body styleClass="errorPage">.- Returns:
- The CSS selector, or
null.
-
setIgnoreSelector
Sets the CSS selector for elements whose presence suppresses error reporting. When an element matching this selector exists in the document, errors will not be sent to the server.- Parameters:
ignoreSelector- The CSS selector.
-
getMaxRecentErrors
public int getMaxRecentErrors()Returns the maximum number of recent errors to keep for deduplication. Defaults to 100.- Returns:
- The maximum number of recent errors.
-
setMaxRecentErrors
public void setMaxRecentErrors(int maxRecentErrors) Sets the maximum number of recent errors to keep for deduplication. Defaults to 100.- Parameters:
maxRecentErrors- The maximum number of recent errors.
-
getErrorExpiry
public int getErrorExpiry()Returns the time in milliseconds after which a recent error entry expires. Defaults to 60000 (1 minute).- Returns:
- The error expiry time in milliseconds.
-
setErrorExpiry
public void setErrorExpiry(int errorExpiry) Sets the time in milliseconds after which a recent error entry expires for deduplication. Defaults to 60000 (1 minute).- Parameters:
errorExpiry- The error expiry time in milliseconds.
-
registerServletIfNecessary
Register the script error handler servlet if it has not already been registered and there is at least one CDI observer forScriptError.- Parameters:
servletContext- The involved servlet context.
-