原文网址:SpringBoot全局处理系列--全局异常处理_IT利刃出鞘的博客-CSDN博客
简介
说明
本文用实例介绍SpringBoot如何进行全局异常处理。
系列文章
SpringBoot全局处理我写了一个系列 :
- SpringBoot全局处理系列--@ControllerAdvice_IT利刃出鞘的博客-CSDN博客
- SpringBoot全局处理系列--全局异常处理_IT利刃出鞘的博客-CSDN博客
- SpringBoot全局处理系列--全局响应处理_IT利刃出鞘的博客-CSDN博客
- SpringBoot全局处理系列--全局请求处理_IT利刃出鞘的博客-CSDN博客
- SpringBoot全局处理系列--全局格式处理_IT利刃出鞘的博客-CSDN博客
实例:简单测试
测试代码
controller
package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/advice")
public String test() {
int i = 1 / 0;
return "test success";
}
}
测试
访问:http://localhost:8080/advice
前端结果:
{
"message": "全局异常处理/ by zero"
}
后端结果:
2021-08-18 00:39:20.240 ERROR 31064 --- [nio-8080-exec-1] c.example.config.GlobalExceptionAdvice : / by zero
java.lang.ArithmeticException: / by zero
at com.example.controller.HelloController.test(HelloController.java:11) ~[classes/:na]
...
实例:项目实战
测试代码
Controller
package com.example.business.controller;
import com.example.business.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("fault")
public void fault() {
int i = 1 / 0;
}
}
测试
postman访问:http://localhost:8080/user/fault
postman结果
后端结果
代码
上边是本文的部分内容,为便于维护,全文已转移到此网址:SpringBoot–全局异常处理 - 自学精灵