zoukankan      html  css  js  c++  java
  • SpringBoot 异常处理

    SpringBoot 异常处理

    一、自定义错误页面

      创建 error.html 页面,当发生错误时,将自动跳转到该页面。内部实现类为:BasicErrorController

      适用范围:所有的异常都指向 error.html 页面,不能根据对应的异常跳转到对应的页面。

    二、@ExceptionHandler

      在对应的Controller内,添加对应的错误处理方法,然后跳转到指定的错误页面。

      适用范围:每个Controller内都有对应的错误方法,代码冗余性高。

    三、@ControllerAdvice 全局异常处理器注解

      搭配@ExceptionHandler 使用,可以解决方式二的代码冗余问题。

      

    四、SimpleMappingExceptionResolver   

    @Configuration   //当配置类使用
    public class GlobalException {
    
        @Bean      //返回异常处理bean
        public SimpleMappingExceptionResolver getGlobalException() {
            SimpleMappingExceptionResolver smer = new SimpleMappingExceptionResolver();
            Properties mappings = new Properties();
            mappings.put("异常类型", "视图名称");
            smer.setExceptionMappings(mappings);
            return smer;
        }
        
    }
    View Code

      适用范围:区别于方式三,方式四无法传递异常对象。

    五、HandlerExceptionResolver

      实现 HandlerExceptionResolver,重写 resolveException 方法

    @Configuration
    public class GlobalException extends HandlerExceptionResolverComposite{
    
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) {
            ModelAndView mv = new ModelAndView();
            //添加异常分支处理
            if(ex instanceof NullPointerException) {
                mv.setViewName("视图名称");
            }
            if(ex instanceof ArithmeticException) {
                mv.setViewName("视图名称");
            }
            mv.addObject("error", ex.toString()); //传递异常对象
            return mv;
        }
        
    }
    View Code

      适用范围:与方式三类似。

  • 相关阅读:
    Palindrome
    Girls' research
    最长回文
    Water Tree
    Alternating Current
    Psychos in a Line
    Feel Good
    Color the Fence
    javaScript内置类Date,Math等
    DOM之兄弟节点
  • 原文地址:https://www.cnblogs.com/chen--biao/p/10134841.html
Copyright © 2011-2022 走看看