【发布时间】:2019-07-08 10:07:02
【问题描述】:
我最近偶然发现了一些我以前在这种形式中没有见过的代码。也许这里有人可以帮助我更好地了解发生了什么。
也就是说,我找到了一个用@RequestMapping 和 @ExceptionHandler 注释的方法。我认为前者用于处理请求,而后者用于处理异常,所以我认为通常使用两个注释中的 either,而不是 both同一时间。
代码sn-p是:
@RequestMapping(produces = "application/json")
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody ErrorEntity handleServiceException(Exception exception) {
log.error(exception.getMessage(), exception);
ErrorEntity errorEntity = createErrorEntity(null, exception.getMessage(),
exception.getLocalizedMessage());
return errorEntity;
}
我有两个问题:
- 根据Spring documentation on
@RequestMapping,@RequestMapping方法的未注释方法参数(不是某些特殊类型)被隐式注释为@ModelAttribute(参见“任何其他参数” 在上述链接下的表格末尾)。那么在上面的代码sn-p中,Exception参数是不是也隐式地用@ModelAttribute注释了呢?如果是,这有意义吗? - 用
@RequestMapping和@ExceptionHandler来注释方法通常有意义吗(例如,同时处理请求和异常),还是这样的形式不好?
【问题讨论】:
-
这里
@RequestMapping用于仅定义响应类型而不用于请求 url 映射,@ExceptionHandler用于清除 Exception 类的映射,因此如果在应用程序中的任何位置,任何控制器方法都会抛出异常这个方法会执行。
标签: java spring spring-mvc request-mapping