Spring MVC: Get i18n message for reason in @Reques

2019-06-14 14:01发布

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 !

2条回答
可以哭但决不认输i
2楼-- · 2019-06-14 14:57

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 (since RestController extends Controller). Second, I had to annotate it @ResponseBody to make sure 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 {}
查看更多
Viruses.
3楼-- · 2019-06-14 14:58

If you put exception handlers into classes annotated with @ControllerAdvice, you can configure this advice to match particular controllers by specifying annotation attribute.

In your case, simply create separate advices 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
    ...
}
查看更多
登录 后发表回答