I recently stumbled upon some code that I had not seen in this form before. Maybe someone here can help me understand better what's going on.
Namely, I found a method annotated both with @RequestMapping
and @ExceptionHandler
. I thought that the former were for handling requests, while the latter were for handling exceptions, so I would have thought one normally uses either of both annotations, but not both at the same time.
I found the code snippet here: https://github.com/shopizer-ecommerce/shopizer/blob/2.5.0/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java#L24
The code snippet is:
@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;
}
I have two questions:
- According to the Spring documentation on
@RequestMapping
, un-annotated method parameters (that are not of some special type) of a@RequestMapping
method are implicitly annotated with@ModelAttribute
(see "Any other argument" at the end of the table under the above link). So in the above code snippet, is theException
parameter implicitly annotated with@ModelAttribute
as well? And if yes, does that make sense? - Can it generally make sense to annotate a method with both
@RequestMapping
and@ExceptionHandler
(e.g., to handle both requests and exceptions), or would that be bad form?