Search code examples
jsfconverterscustom-renderer

How to tell the Renderer that an ConversionException occured?


I got a bit stuck while taking my first baby steps with Custom Components in JavaServer Faces 2.2 (Jakarta Server Faces).

My problem is, how can a renderer class know, if a ConverterException was thrown? I need this check in my renderer, because I want the renderer to apply a 'invalid' class to the HTML input tag. The converter is used only for this Custom Component.

Here are some things I looked into, but I am not confident any of these this is the right approach.

  1. The method is isValidationFailed from FacesContext does not apply to conversion errors. So this is a dead end.

  2. I could create my own class from UIInput with a attribute 'invalid' and set this in the getAsObject method of the Converter class in case anything breaks. The renderer then checks the property of the component class.

  3. I could iterate over getMessages from FacesContext and look for a message from the converter.

  4. I can use the h:message approach and do some JavaScript DOM manipulation on the client side. If I find a h:message with a specific class, I apply another class to the input tag.

  5. Skip the renderer and do the rendering in the component class. Not sure if this gives me anything though.

Thanks in advance!


Solution

  • Given these facts:

    • The component is an UIOutput.
    • You're interested in whether getAsString() throws an exception, and thus not whether getAsObject() throws an exception (that's only for UIInput components and it's normally only invoked when submitted input values need to be converted to bean properties).
    • The converter is (indirectly) invoked by the renderer.

    Then the answer is to simply put the converter call in a try-catch. E.g.

    Object modelValue = getValue();
    String outputValue;
    
    try {
        outputValue = getConverter().getAsString(context, component, modelValue);
    }
    catch (ConverterException e) {
        outputValue = "Conversion error occurred! " + e.getMessage();
    }
    
    responseWriter.write(outputValue);