SpringMVC-RESTEasy 和异常映射
我正在使用 RESTEasy Spring MVC 集成(springmvc-resteasy 使用 RestEasy 2.0、Spring 3.0) 我想通过声明 RESTEasy 异常映射提供程序将应用程序异常映射到 HTTP 响应。目前,我的应用程序没有显式扩展 javax.ws.rs.core.Application ,理想情况下我希望依赖框架对异常映射提供程序的自动扫描。
这是我的异常映射器之一的样子。
@Provider public class MyAppExceptionMapper implements ExceptionMapper<MyAppException> {
public Response toResponse(MyAppException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
我的异常类看起来像这样
public class MyAppException extends RuntimeException {
public MyAppException(String s, Throwable t) {
super(s,t);
}
}
当我的应用程序抛出 MyAppException
时,它不会映射到 HTTP-400 响应(我从框架获得通常的 HTTP-500)
是否有我遗漏的东西?如果这是未向框架“注册”提供程序的问题,那么当我使用 springmvc-resteasy 时如何注册我的异常映射器?
谢谢。
I am using the RESTEasy Spring MVC integration (springmvc-resteasy using RestEasy 2.0, Spring 3.0) I would like to map my application exceptions to HTTP responses by declaring the RESTEasy exception mapping providers. Currently my application does not explicitly extend javax.ws.rs.core.Application
and ideally I would like to rely on the framework's automatic scanning of exception mapping providers.
Here is what one of my exception mappers looks like.
@Provider public class MyAppExceptionMapper implements ExceptionMapper<MyAppException> {
public Response toResponse(MyAppException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
And my exception class looks like this
public class MyAppException extends RuntimeException {
public MyAppException(String s, Throwable t) {
super(s,t);
}
}
When my application throws a MyAppException
, it does not get mapped to a HTTP-400 response (I get the usual HTTP-500 from the framework)
Is there something I am missing? If this is a problem with not "registering" the provider with the framework, how do I register my exception mappers when I am using springmvc-resteasy?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我收到了 Solomon Duskis 的回复,我将其发布在这里,以确保遇到此问题的其他人能够快速解决。正如我所怀疑的,我必须以某种方式配置 Spring 来配置 RESTEasy 来扫描我的异常映射提供程序。我向异常映射器添加了一个 @Component,它确实可以将 MyAppException 映射到正确的 HTTP 响应代码(在本例中为 400,而不是 500)。但是,这里有一个警告:RESTEasy 不会序列化 MyAppException,因为“java.lang.StackTraceElement 没有无参数默认构造函数”。我正在寻找这个次要问题的解决方案。
I received an answer from Solomon Duskis that I am posting here to make sure other folks who run into this issue can solve it quickly. As I suspected, I had to somehow configure Spring to configure RESTEasy to scan for my exception mapping provider. I added a
@Component
to my exception mapper and it does work for mapping MyAppException to the right HTTP response code (in this case 400 instead of 500). However, here's a caveat: MyAppException is not serialized by RESTEasy because "java.lang.StackTraceElement does not have a no-arg default constructor." I am looking for a solution for this secondary issue.