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

一笑奈何 提交于 2020-01-03 05:10:10

问题


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 !


回答1:


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
    ...
}



回答2:


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 {}


来源:https://stackoverflow.com/questions/29273419/spring-mvc-get-i18n-message-for-reason-in-requeststatus-on-a-exceptionhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!