Why are error pages ignored in RESTEasy web service running on Tomcat?

百般思念 提交于 2020-01-03 05:09:07

问题


I'm developing a REST-ful web service using RESTEasy deployed on Tomcat. I've configured an error page which takes the exception's message and generates an XML based on it when any exception occurs during the request.

This works fine for any application generated exceptions. However, if client sends an invalid XML which cannot be unmarshalled correctly, an javax.xml.bind.UnmarshalException is thrown and Tomcat's default error page is used instead of mine.

I have configured my error page to the error-code 500 in web.xml.

Is using error pages the correct way to handle errors when using RESTEasy or is there an alternative way?


回答1:


The best way is to use an ExceptionMapper. You create a class UnmarshalExceptionMapper that implements ExceptionMapper. You annotate this with "@Provider" and in your Application constructor you do "classes.add(UnmarshalExceptionMapper.class)" or "singletons.add(new UnmarshalExceptionMapper())".

Your exception mapper will look something like this:

 @provider
 public class UnmarshalExceptionMapper 
            implements ExceptionMapper<UnmarshalException> {
    public Response toResponse(UnmarshalException exception) {
        ResponseBuilder rb =
            Response.status(
                  Response.Status.BAD_REQUEST)  // Most appropriate HTTP status code
            .entity(your xml goes here)
            .type("application/xml");  
        return rb.build();
   }
 }

Note that you must set the type to "application/xml" because currently content negotiation is NOT done for exception mappers. To do your own content negotiation, get the HttpHeaders from the request, find the "accept" header, and set the type accordingly.



来源:https://stackoverflow.com/questions/2377465/why-are-error-pages-ignored-in-resteasy-web-service-running-on-tomcat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!