Introduction
One of the holes in JSF, in my professional judgement, is the lack of really good exception handling on the client for AJAX exceptions. A number of client frameworks like PrimeFaces, OmniFaces, and RichFaces attempt to cleanup for this shortcoming, it is still a deficiency.The capabilities are present to make AJAX exception handling more robust. The "chemistry" is present in the framework, but it is not really standardized.
In this short example, I am demonstrating how to use the
jsf.ajax.addOnError
functionality to make client exception handling better. We will display at a minimum, an alert to let them know something bad has happened to their request.Additionally, I will demonstrate how to use XPath to get additional information from the response.
Solution
The solution is to add the following code to the<head />:
of the JSF page, or to an external JavaScript file that is included in the head. In my case, I am using an external JS file called jsf.ajax.handler.js
that is loaded using JSF <h:outputScript />
.
1 | < h:outputScript library = "js" target = "head" name = "jsf.ajax.handler.js" /> |
Here are the contents of the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /* * Copyright 2012-2014 John Yeary <jyeary@bluelotussoftware.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ jsf.ajax.addOnError( function (data) { // This shows how to get the information via XPath, but it is not required. The error name can be found using data.errorName var errorName = data.responseXML.evaluate( '//error/error-name' , data.responseXML, null , XPathResult.STRING_TYPE, null ); var message = 'AJAX Exception' ; message += '\nSource: ' + data.source.id; message += '\nValue:' + data.source.value; message += '\nError: ' + errorName.stringValue; message += '\nMessage: ' + data.errorMessage; alert(message); //TODO Take Additional actions }); jsf.ajax.addOnEvent( function (data) { alert(data.source.id + " " + data.type + " " + data.status); }); |
References
- jsf.ajax
- Introduction to using XPath in JavaScript
- jsf.ajax.handler.js Gist on GitHub
0 comments :
Post a Comment