Spring MVC: get i18n message for reason in @RequestStatus on @ExceptionHandler

I have a Spring boot application with Thymeleaf that mixes up regular Controller calls that request lookup and REST asynchronous calls. To handle errors in asynchronous REST calls, I would like to provide a property as a reason for handling exceptions and automatically translate it using MessageSource.

My handler is as follows.

@ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "general.unexpected.exception") public ModelAndView handleUnexpectedException(Exception exception) { logger.error(exception.getMessage(), exception); return createModelAndView("error"); } 

When an error occurs as part of a normal controller call, an error message is displayed. But in the case of Javascript REST calls, I would like to be able to replace the reason general.unexpected.exception with the appropriate text based on the user locale, for example, "An unexpected error occurred", so I can display this in the interface in my javascript () failure in case of an unhandled mistakes.

Any clue on how to do this would be greatly appreciated. Thanks!

0
source share
2 answers

If you put exception handlers in classes annotated with @ControllerAdvice , you can customize this tip to match specific controllers by specifying the annotation attribute.

In your case, just create separate tips for @Controller and @RestController and exception handlers with different logic for each:

 @ControllerAdvice(annotations = RestController.class) class RestAdvice { @ExceptionHandler ... } @ControllerAdvice(annotations = Controller.class) class MvcAdvice { @ExceptionHandler ... } 
0
source

I went with Mac, but there are some additional things that I had to do. First, I had to set priority 1 to this @ControllerAdvice to avoid exceptions that should be RestController by others (since RestController extends Controller ). Secondly, I had to annotate it with @ResponseBody to make sure that the return value of my handler would be returned as a REST response.

 @ControllerAdvice(annotations = RestController.class) @Priority(1) @ResponseBody public class RestControllerAdvice {} @ControllerAdvice(annotations = Controller.class) @Priority(2) public class MvcControllerAdvice {} 
0
source

All Articles