1

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:

  1. 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 the Exception parameter implicitly annotated with @ModelAttribute as well? And if yes, does that make sense?
  2. 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?
Malte Skoruppa
  • 1,232
  • 1
  • 19
  • 25
  • Here `@RequestMapping` used to define only response type not for the request url mapping and `@ExceptionHandler` used to clear mapping of Exception class so if any where in application, Exception is getting thrown from any controller method this method will execute. – ypp Jul 08 '19 at 10:12

1 Answers1

0

good question. I would say try this. on a controller, take two methods. on one method use just RequestMethod and write a code by accepting a model attribute from page. On this method, create a scenario for a NullPointerException.

On method 2, annotate both RequestMapping and ExceptionHandler. And you can see whether you are getting the request, response with ModelAttributes from method one to method 2.

if yes, then this would help us evaluate the exception and handle invalid scenarios where we would need the model attribute values.

Also as per the explanation that you have pasted above, ModelAttribute is implicit for RequestMapping, not for all annotations on a controller method.

Please let us know.

Srini M
  • 495
  • 2
  • 9