java 使用@ExceptionHandler 在 Spring MVC 中处理“错误 500”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13664933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:33:03  来源:igfitidea点击:

Handling "error 500" in Spring MVC using @ExceptionHandler

javaspringmodel-view-controllererror-handling

提问by mic4ael

(Firstly, I must say that I have been looking for answers on stackoverflow and the internet but haven't found sufficient answers)**I have just started my adventure with Spring MVC and my first task is to handle Internal Server Error using @ExceptionHandler annotation (first of all, i got to point out that I don't want to use error-page in web.xml). Briefly, whenever "error 500" occurs, there ought to be displayed a proper site with a link to the home site. So, my problem is that I don't know how to make method which follows @ExceptionHandler(Exception.class)invoked each time error 500 takes place.

(首先,我必须说我一直在寻找关于 stackoverflow 和互联网的答案,但还没有找到足够的答案)**我刚刚开始我的 Spring MVC 冒险,我的第一个任务是使用 @ExceptionHandler 处理内部服务器错误注释(首先,我必须指出我不想在 web.xml 中使用错误页面)。简而言之,无论何时发生“错误 500”,都应该显示一个带有指向主站点的链接的正确站点。所以,我的问题是我不知道如何制作@ExceptionHandler(Exception.class)每次发生错误 500 时调用的方法。

回答by Md. Kamruzzaman

If you use java configuration you may try like follows:

如果您使用 java 配置,您可以尝试如下:

@Configuration
public class ExcpConfig {

    @Bean(name = "simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver= new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        resolver.setExceptionMappings(mappings); // None by default
        resolver.setExceptionAttribute("ErrorOccurred"); // Default is "exception"
        resolver.setDefaultErrorView("500"); // 500.jsp
        return resolver;
    }

}

回答by Jimadilo

You can't actually do what you want with the @ExceptionHandler annotation. This is only for exceptions in a specific controller, not for more general things like error 500's.

你实际上不能用 @ExceptionHandler 注释做你想做的事。这仅适用于特定控制器中的异常,不适用于更一般的事情,例如错误 500。

You probably want to look at implementing the HandlerExceptionResolver interface, and wiring that in for more general exceptions.

您可能想要查看实现 HandlerExceptionResolver 接口,并将其连接到更一般的异常中。

Here's a link to it in the spring docs.

这是 spring 文档中的链接。

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers

Let me know if you need any other help.

如果您需要任何其他帮助,请告诉我。