I have a Spring boot app with Thymeleaf mixing normal Controller calls that fetch views and REST async calls. For error handling in REST async calls, I would like to be able to provide a property as reason in exception handling and have it translated automatically by a MessageSource.
My handler is as follow.
@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, the error view is displayed. But in case of Javascript REST calls I would like to be able to have the general.unexpected.exception
reason replaced by the corresponding text based on the user locale for example "An unexpected error happened" so I can display that in UI in my javascript fail() method in case of unhandled error.
Any clue on how to do that would be appreciated. Thanks !
I went with Maciej answer but there are some additional things I had to do. First, I had to set priority 1 to this
@ControllerAdvice
to avoid exceptions to be picked up by the other one (sinceRestController
extendsController
). Second, I had to annotate it@ResponseBody
to make sure the return value of my handler would be returned as a REST response.If you put exception handlers into classes annotated with
@ControllerAdvice
, you can configure this advice to match particular controllers by specifyingannotation
attribute.In your case, simply create separate advices for
@Controller
and@RestController
and exception handlers with different logic for each: