• 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

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

  • 相关阅读:
    12c oracle grid p28662603 psu 安装---2018年10月最新的补丁
    11g oracle grid p28429134 psu 安装
    infinband 6036 交换机配置管理口IP
    HCA卡测试
    带宽测试
    IB网络基准性能测试
    带着萌新看springboot源码10(springboot+JdbcTemplate+druid)
    带着萌新看springboot源码09(springboot+JdbcTemplate)
    带着萌新看springboot源码8(spring ioc源码 完)
    带着萌新看springboot源码8(spring ioc源码下)
  • 原文地址:https://www.cnblogs.com/chen--biao/p/10134841.html
Copyright © 2020-2023  润新知