0

When my server receives incomplete xml it returns a 500 Internal Server Error back due to the default handling for java.lang.IllegalArgumentException. I can override the html page that is returned but I also need to override the error code and make it 400 to follow our documented spec. Is there a way to override the error code in JSF-2.0? We are using JAXB for the xml handling.

ghimireniraj
  • 397
  • 1
  • 5
Ryland
  • 119
  • 2
  • 13

2 Answers2

1

I ended up using an ExceptionMapper like so:

@Provider
public class ClassCastExceptionMapper implements ExceptionMapper<java.lang.ClassCastException> {

    @Override
    public Response toResponse(java.lang.ClassCastException arg0) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
Ryland
  • 119
  • 2
  • 13
  • Confusing. That's of the JAX-RS API which is totally unrelated to JSF. What exactly was now the problem you were having? Handling exceptions of a JAX-RS webservice which is in turn used by a JSF web frontend? – BalusC Sep 02 '11 at 00:20
0

Depends on where it's been thrown and if it's wrapped in another exception. It's hard to give a perfect-fit answer based on the information provided as far.

But to the point, to send a response error with the right status using JSF2, use ExternalContext#responseSendError(). E.g.

try {
    // ... ???
} catch (IllegalArgumentException e) {
    externalContext.responseSendError(400, e.getMessage());
    e.printStackTrace(); // Or use logger.
}

Or equivalently in a servlet filter, use HttpServletResponse#sendError()

try {
    // ... ???
} catch (IllegalArgumentException e) {
    response.sendError(400, e.getMessage());
    e.printStackTrace(); // Or use logger.
}
Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • I just stepped through our filters and the exception isnt being thrown by one of them but is being thrown by the empty constructor on our top level JAXB class which is used to instantiate the other classes based upon the incoming xml. – Ryland Jul 19 '11 at 13:02
  • The answer here http://stackoverflow.com/questions/3293599/jax-rs-using-exception-mappers/3356277#3356277 ended up solving it for me. I just added an ExceptionMapper which caught the correct type and returned a 400 error. – Ryland Jul 19 '11 at 13:04