1

JSF throws an exception during bean init, no messages, nothing.

public class MyBean {
   @PostConstruct
   public void init() {

       try {

           // some code,
       } catch (Throwable t) {
           // if adding a facesMessage here: it did not show up either

           throw new Exception(t);
       }
   }
}


<html>
<body>
   <h:outputText value="#{mybean.value}"/>

   <f:messages />
</body>

</html>

When an exception is thrown, the response is empty:

<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"></pre></body></html>

How to show a message to let user know in this case?

UPDATE

This question is not a duplicate of the other question specified. This question is about throwing exception during bean initialization, and how to display the exception to end user.

Dave
  • 759
  • 2
  • 9
  • 31
  • 1
    You should *log* the exception. You don't show this sort of thing to users.This is a serious error. JSF cannot proceed with the bean instantiation. – user207421 Mar 01 '17 at 03:28
  • User should know such errors as "permission is not granted." when trying to access sensitive data. The data is fetched during bean init(). – Dave Mar 01 '17 at 12:49
  • I don't know what should be. It must be . If you define at first like you did the faces message should definitely be shown. Did you define the JSF namespaces? They are not in your example. Did you declare MyBean as managed bean? It also doesn't appear in your example. – Alex Fire Mar 01 '17 at 19:01

1 Answers1

3

How to show a message to let user know in this case?

See FacesContext#addMessage

In your catch block, provide a message suitable for display to user, something that does not reveal any critical application or security details.

FacesMessage facesMessage = new FacesMessage("Something went wrong"); FacesContext facesContext = FacesContext.getCurrentInstance(); facesContext.addMessage(null, facesMessage);

This example of addMessage() specifies null as clientId in argument one. Thus, your <f:messages> will display all messages which are not directed to a specific client ID.

To direct messages to a specific message component in the page, then define this component with a unique ID <f:message id="idSingleMessage"/> and direct messages to it by specifying the clientId: facesContext.addMessage("idSingleMessage", facesMessage);

You can also add JSF Severity Levels to render different markup styles in the message.

Finally, you can use a logging library such as log4j or slf4j to log the specific error to a file.
Apache Exception Utils can simplify this for you.

J Slick
  • 929
  • 11
  • 17
  • SLF4J is not a typical logging library. It is a logging facade that abstracts the underlying logging framework. As underlying framework you can use log4j or other logging libraries that are supported by SLF4J. – Alex Fire Mar 01 '17 at 18:57