I'm using JSF 2 and I'm getting some exception while I'm using some web service and I want to catch that exception and display the message on my .xhtml
page.
How can I do that?
I'm using JSF 2 and I'm getting some exception while I'm using some web service and I want to catch that exception and display the message on my .xhtml
page.
How can I do that?
You can use the try-catch
block to catch and handle the exception. You can use FacesContext#addMessage()
to add a faces message to the faces context. You can use <h:messages>
to display faces messages.
So, something like this in the bean:
try {
data = yourWebService.retrieve();
} catch (YourWebServiceException e) {
String message = "Failed to retrieve data from webservice: " + e.getMessage());
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
e.printStackTrace(); // Or use a logger.
}
And this in the JSF page:
<h:messages globalOnly="true" />
(the globalOnly="true"
will force the <h:messages>
to only show messages with a null
client ID)
To give you an example to what BalusC has explained, you could write a simple method that gets called in a catch statement.
private void addErrorMessage(String msg, String clientId) {
String codingErrorMsgKey = "coding_error_msg";
FacesMessage fm;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (StringUtils.isEmpty(msg)) {
ResourceBundle bundle = facesContext.getApplication().getResourceBundle(facesContext, "bundle");
fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle.getString(codingErrorMsgKey), bundle.getString(codingErrorMsgKey));
}
else {
fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
}
facesContext.addMessage(clientId, fm);
}
What the method does is really simple : you give it a message that you may have resolved earlier form your application's resource bundle, then a global (only if clientId is null) error (because of FacesMessage.SEVERITY_ERROR
) FacesMessage
is created. The created error message is then added to the facesContext
using a default string as the message if you didn't provide any.
Since this method is able to create global and clientId-related error messages, you won't have to use globalOnly
property. Simply specify <h:messages/>
to have the tag display all of your messages (global or not).
Again, this only is sample code. You may have to adjust/improve to make it your own. Also, you could almost duplicate this method to handle information messages.
As a generic way of dealing with error messages, you could make this method available in a super class that every controller would then extend.