zoukankan      html  css  js  c++  java
  • SpringMVC统一异常处理(Controller处理)

    1、  在一个controller内的统一处理示例

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    @RestController
    public class TestCtl {
    
        @RequestMapping("/ready")
        public String ready(){
                throw new RuntimeException("ready抛出的异常");
        }
        
        @ExceptionHandler
        public String ExceptionHandler(Exception e) {
                return e.getMessage();
        }
    }

    请求结果:

    也可以自定义Exception,但最好是RuntimeException的子类,以避免“检查异常”必须被处理而造成代码冗余;

        @ExceptionHandler是Spring MVC已有的注解,可用于Controller、ControllerAdvice、RestControllerAdvice类的异常处理。

    2、 使用ControllerAdvice对同一类异常做统一处理示例:

    Controller

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestCtl {
    
        @RequestMapping("/ready")
        public String ready(){
                throw new RuntimeException("ready抛出的异常");
        }
    }

     统一异常拦截类

    import org.springframework.core.annotation.Order;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    @Order(0)
    @RestControllerAdvice(annotations = RestController.class)
    public class RestCtlAdvice {
    
    @ExceptionHandler
    @ResponseBody //RestControllerAdvice中无需添加此注解,同RestController
        public String ExceptionHandler(Exception e) {
                return e.getMessage();
        }
    }

         最后运行结果同1,RestCtlAdvice会对所有RestController中的异常进行处理,如果是Exception(此可以是自定义的特定异常的精细处理)类型异常,RestCtlAdvice类可以有多处,处理顺序按照给定的order来运行。RestController.class也可以替换为Controller.class,则对所有Controller的异常进行拦截。 

         Java 异常体系设计的目的在于通过使用少量代码,实现大型、健壮、可靠程序。异常处理是 Java 中唯一正式的错误报告机制。异常处理机制最大的好处就是降低错误代码处理的复杂程度。

          如果不使用异常,那么就必须在调用点检查特定的错误,并在程序的很多地方去处理它;如果使用异常,那么就不必在方法调用处进行检查,因为异常机制将保证能够捕获这个错误。因此只需要在一个地方处理错误,这种方式不仅节省代码,而且把“描述正确执行过程做什么事”和“出了问题怎么办”相分离。

  • 相关阅读:
    狼羊过河问题
    java实现透明窗体
    商人胡萝卜问题
    NXP迅为IMX8开发板Andaoid编译环境搭建
    迅为龙芯2K1000开发板Linux下gcc编译
    迅为恩智浦i.MX8MM开发平台虚拟机安装Ubuntu16.04系统
    恩智浦NXP迅为i.MX6Q开发板资料提升了
    迅为龙芯2K1000开发板Linux工具之make工具和Makefile文件
    迅为瑞芯微3399开发板minimalYocto文件系统的构建
    迅为恩智浦IMX6Q开发板Buildroot 文件系统 alsa 声卡工具测试
  • 原文地址:https://www.cnblogs.com/aland-1415/p/12604752.html
Copyright © 2011-2022 走看看