我做了一个像sample这样的项目。控制器是这样的
package mypackagename.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/")
public class StoresRestController {
@RequestMapping(method = RequestMethod.GET)
public String stores() {
return ...
}
}
我喜欢处理所有的throwables,并作出我的定制统一的响应。问题是我找不到一个指南或样本来正确地做到这一点。
首先,我尝试了ExceptionHandler
和Throwable
,但是没有效果,所以我决定继续。然后,我发现最接近的方法是this,所以我尝试了jersey,添加了类似this的东西。但是它并不是对所有的throwables都有效。而且,它会通过抱怨忽略我的控制器
o.g.jersey.internal.inject.Providers : A provider mypackagename.controller.StoresRestController registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider mypackagename.controller.StoresRestController will be ignored.
我搜索了这个错误,发现了this,我没有在我的项目中使用ContainerResponseFilter
,因为我提供了上面的例子。所以我一无所知。主要的问题是如何处理所有的throwables,但如果你能给予我一些关于如何解决Providers
问题的建议,我将非常感激。
3条答案
按热度按时间nhaq1z211#
在我的项目中,我使用@ControllerAdvice来处理我的异常。这里有一个例子。希望这能有所帮助。只要确保这个类在你的组件扫描中,这样它就能被选中。
avkwfej42#
最后this post帮助我处理了所有的
Throwable
,除了验证异常。重要的部分是使用@EnableWebMvc
和ResponseEntityExceptionHandler
。为了处理验证异常,我使用了this answer。希望它能帮助到一些人。mrphzbgm3#
正如@carlos-cook所说,您可以使用RFC 7807中定义的
@ControllerAdvice
和ProblemDetail
,如下所示:然后在控制器中,您可以简单地抛出
YourCustomException
这个控制器通知将分别处理每个异常和YourCustomException。