spring - 防止网页上出现Spring错误

标签 spring spring-mvc error-handling

我正在使用Spring MVC 3。
我验证各种用户的输入并显示适用的错误。

但这经常显示在用户界面上显示诸如org.springframework.core.convert.ConversionFailedException等的spring错误。如何防止这些错误在网页上输出?

最佳答案

Note:

I understand that for topic starter my answer may be no longer relevant. But it can be useful for those who have visited this page to search for solutions to similar problems.



回答:

为了防止在网页上输出错误,您可以进行处理。在Spring MVC 3.x及更高版本中,可以使用几种类型的错误处理:
  • 基于 Controller 的异常处理
  • 全局异常处理
  • Other methods, that are bit more complicated

  • 基于 Controller 的异常处理

    您可以在 Controller 内部的方法上添加@ExceptionHandler批注。对于从同一 Controller 中标注为@RequestMapping的方法引发的异常,此类方法将充当错误处理程序。
    @ExceptionHandler(Exception.class)
    public ModelAndView handleError(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", req.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }
    

    全局异常处理

    Controller 建议使您可以将异常处理应用于整个应用程序,而不仅仅是单个 Controller 。换句话说,处理将应用于从任何 Controller 引发的异常。
    @ControllerAdvice
    class GlobalControllerExceptionHandler {
        public static final String DEFAULT_ERROR_VIEW = "error";
    
        @ExceptionHandler(Exception.class)
        public void handleError(HttpServletRequest req, Exception e) {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception", e);
            modelAndView.addObject("url", req.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
            return modelAndView;
        }
    }
    

    For more info:

    关于spring - 防止网页上出现Spring错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798693/

    相关文章:

    java - Spring security不解析xml

    asp.net-mvc - ASP.NET MVC 4 : Handle exception caused by JsonValueProvider

    java.lang.ClassNotFoundException : org. glassfish.jersey.internal.RuntimeDelegateImpl ,抛出 BadRequestException 时

    java - 我如何以编程方式为 Spring Boot 和 Tomcat 提供 keystore 文件?

    java - 拦截所有从 Java 应用程序发出的 HTTP 请求

    java - 使用 IDE 运行 Spring-boot 的 main

    java - Whitelabel 错误页面出现意外错误(type=Not Found,status=404)./WEB-INF/views/home.jsp

    java - Spring Boot 忽略 Rest Controller 中的 Jackson 注释

    Swift Combine 接收器在第一次错误后停止接收值

    java - 无法解决方法占位符 fragment 错误