我有一个Spring启动应用程序,Thymeleaf混合了正常的Controller调用,用于获取视图和REST异步调用。 对于REST异步调用中的错误处理,我希望能够在异常处理中提供属性作为原因,并由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原因替换为基于用户区域设置的相应文本,例如“发生意外错误”,这样我就可以在我的javascript中在UI中显示未处理错误时的fail()方法。
任何关于如何做到这一点的线索将不胜感激。 谢谢 !
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 !
最满意答案
如果将异常处理程序放入使用@ControllerAdvice注释的类中,则可以通过指定annotation属性来配置此建议以匹配特定控制器。
在您的情况下,只需为@Controller和@RestController创建单独的建议,并为每个建议使用不同逻辑的异常处理程序:
@ControllerAdvice(annotations = RestController.class) class RestAdvice { @ExceptionHandler ... } @ControllerAdvice(annotations = Controller.class) class MvcAdvice { @ExceptionHandler ... }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 ... }更多推荐
发布评论