Spring MVC:在@ExceptionHandler上的@RequestStatus中获取原因的i18n消息 [英] Spring MVC: Get i18n message for reason in @RequestStatus on a @ExceptionHandler

查看:101
本文介绍了Spring MVC:在@ExceptionHandler上的@RequestStatus中获取原因的i18n消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Thymeleaf的Spring boot应用程序,混合了获取视图和REST异步调用的常规Controller调用。对于REST异步调用中的错误处理,我希望能够提供一个属性作为异常处理的原因,并使其由MessageSource自动转换。

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.

我的处理程序是

@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"); 
}

在正常控制器调用中发生错误时,错误视图为显示。但是,对于Javascript REST调用,我希望能够将 general.unexpected.exception 原因替换为基于用户区域设置的相应文本,例如意外错误发生,这样我就可以在UI中的javascript fail()方法中显示该错误,以防出现未处理的错误。

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 !

推荐答案

如果将异常处理程序放入带有 @ControllerAdvice ,您可以通过指定 annotation 属性将该建议配置为与特定控制器匹配。

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

在您的情况下,只需为 @Controller @RestController创建单独的建议和具有不同逻辑的异常处理程序:

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

这篇关于Spring MVC:在@ExceptionHandler上的@RequestStatus中获取原因的i18n消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆