为什么在Tomcat上运行的RESTEasy Web服务中忽略错误页面? [英] Why are error pages ignored in RESTEasy web service running on Tomcat?

查看:211
本文介绍了为什么在Tomcat上运行的RESTEasy Web服务中忽略错误页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tomcat上部署的RESTEasy开发REST REST Web服务。我已经配置了一个错误页面,该页面接受异常的消息,并在请求期间发生任何异常时根据它生成一个XML。



对于任何应用程序生成的异常。但是,如果客户端发送无法正确解组的无效XML,则抛出 javax.xml.bind.UnmarshalException ,并使用Tomcat的默认错误页,而不是我的。 p>

我将错误页面配置到web.xml中的错误代码500。



使用错误页面使用RESTEasy处理错误的正确方法还是有替代方法?

解决方案

最好的方法是使用ExceptionMapper。您创建一个实现ExceptionMapper的类UnmarshalExceptionMapper。您可以使用@Provider注释并在您的应用程序构造函数中执行classes.add(UnmarshalExceptionMapper.class)或singletons.add(new UnmarshalExceptionMapper())。



您的异常映射器将如下所示:

  @provider 
public class UnmarshalExceptionMapper
implements ExceptionMapper< UnmarshalException> {
public Response toResponse(UnmarshalException exception){
ResponseBuilder rb =
Response.status(
Response.Status.BAD_REQUEST)//最适合的HTTP状态代码
。实体(你的xml到这里)
.type(application / xml);
return rb.build();
}
}

请注意,您必须将类型设置为application / xml,因为当前内容协商不是为异常映射器完成的。要做自己的内容协商,从请求中获取HttpHeaders,找到accept头,并相应地设置类型。


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?

解决方案

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.

这篇关于为什么在Tomcat上运行的RESTEasy Web服务中忽略错误页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆