【发布时间】:2016-12-16 19:10:15
【问题描述】:
Spring 3.2.15,此处是基于 MVC 的 REST API(不是 Spring Boot,很遗憾!)。我正在尝试实现满足以下条件的异常映射器/处理程序:
- 无论发生什么(成功或错误),Spring 应用程序始终返回
MyAppResponse的响应实体(见下文);和 - 在成功处理请求的情况下,返回 HTTP 状态 200(典型);和
- 在处理请求发生异常时,我需要控制特定异常到特定HTTP状态码的映射
- Spring MVC 框架错误(如
BlahException)必须映射到 HTTP 422 - 自定义app异常,比如我的
FizzBuzzException有自己的状态映射方案:-
FizzBuzzException-> HTTP 401 -
FooBarException-> HTTP 403 -
OmgException-> HTTP 404
-
- 所有其他异常,即非 Spring 异常和非自定义应用程序异常(上面列出的 3 个)都应该产生 HTTP 500
- Spring MVC 框架错误(如
MyAppResponse 对象在哪里:
// Groovy pseudo-code
@Canonical
class MyAppResponse {
String detail
String randomNumber
}
它似乎像ResponseEntityExceptionHandler 可能能够为我做到这一点,但我没有看到森林通过树木w.r.t。它是如何传递参数的。我希望我可以做类似的事情:
// Groovy-pseudo code
@ControllerAdvice
class MyAppExceptionMapper extends ResponseEntityExceptionHandler {
ResponseEntity<Object> handleFizzBuzzException(FizzBuzzException fbEx, HttpHeaders headers, HttpStatus status) {
// TODO: How to reset status to 401?
status = ???
new ResponseEntity(fbEx.message, headers, status)
}
ResponseEntity<Object> handleFooBarException(FooBarException fbEx, HttpHeaders headers, HttpStatus status) {
// TODO: How to reset status to 403?
status = ???
new ResponseEntity(fbEx.message, headers, status)
}
ResponseEntity<Object> handleOmgException(OmgException omgEx, HttpHeaders headers, HttpStatus status) {
// TODO: How to reset status to 404?
status = ???
new ResponseEntity(omgEx.message, headers, status)
}
// Now map all Spring-generated exceptions to 422
ResponseEntity<Object> handleAllSpringExceptions(SpringException springEx, HttpHeaders headers, HttpStatus status) {
// TODO: How to reset status to 422?
status = ???
new ResponseEntity(springEx.message, headers, status)
}
// Everything else is a 500...
ResponseEntity<Object> handleAllOtherExceptions(Exception ex, HttpHeaders headers, HttpStatus status) {
// TODO: How to reset status to 500?
status = ???
new ResponseEntity("Whoops, something happened. Lol.", headers, status)
}
}
知道如何完全实现此映射逻辑以及实体是MyAppResponse 实例而不仅仅是字符串的要求吗?
那么,使用 @ControllerAdvice 注释类是我配置 Spring 以使用它唯一需要做的事情吗?
【问题讨论】:
标签: spring-mvc exception-handling httpresponse