SpringBoot全局异常处理类

1.添加SpringBoot依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
       <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
     </dependency>
</dependencies>

2.写全局异常处理类及写方法,添加一些注解,如下图所示

@ControllerAdvice
public class GlobalDefaultException {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String defaultExceptionHandler(HttpServletRequest req,Exception e){
        return "系统繁忙,请稍后重试!";
    }
}

3.测试

@RestController
public class TestContoller {

    @RequestMapping("/test")
    public String test(){
        Integer.parseInt("a");
        return "test2";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40333020/article/details/82458375