【发布时间】:2017-06-17 11:15:31
【问题描述】:
我将 Spring MVC 与 Spring Boot 和 Thymeleaf 一起使用。我有返回 Thymeleaf 模板名称的普通控制器和带有 @RepsonseBody 注释的 REST 控制器。
假设我有一个EntityNotFoundException,它由控制器调用的某些代码抛出。如果被抛出,我想分别返回 404 状态码和 REST 控制器的错误页面或错误消息。
我目前对普通控制器的设置:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@Controller
public class FooController {
@RequestMapping("/foo") public String foo() {
try {
...
} catch (EntityNotFoundException enfe) {
throw new ResourceNotFoundException(enfe.getMessage());
}
return "foo";
}
}
对于 REST 控制器,我不会捕获异常,而是让全局异常处理程序来处理它:
@Controller
public class BarController {
@RequestMapping("/bar")
@ResponseBody
public SomeDto bar() throws EntityNotFoundException {
...
return someDto;
}
}
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<Object> handleEntityNotFoundExceptionEntityNotFoundException enfe) {
return new ResponseEntity<>(enfe.getMessage, HttpStatus.NOT_FOUND);
}
}
我也不想在我的普通控制器中捕捉并重新抛出。全局处理程序应该同时处理这两个:
@ExceptionHandler(EntityNotFoundException.class)
public final Object handleEntityNotFoundException(EntityNotFoundException enfe) {
if (/* is REST controller? */) {
return new ResponseEntity<>(enfe.getMessage(), HttpStatus.NOT_FOUND);
} else {
Map<String, Object> model = ImmutableMap.of("message", enfe.getMessage());
return new ModelAndView("error", model, HttpStatus.NOT_FOUND);
}
}
有没有办法确定异常的来源,即控制器是否用@ResponseBody或类似的东西注释?
【问题讨论】:
标签: java spring spring-mvc