SpringBoot——全局捕获异常

释放双眼,带上耳机,听听看~!

@ExceptionHandler 表示拦截异常

@ControllerAdvice   controller 的一个辅助类,最常用的就是作为全局异常处理的切面类

1. 定义全局异常类


1
2
3
4
5
6
7
8
9
10
11
12
13
1@ControllerAdvice   // 切面
2public class GlobalExceptionHandler {
3    // 捕获运行时异常
4    @ExceptionHandler(RuntimeException.class)
5    @ResponseBody
6    public Map<String,Object> exceptionHander(){
7        Map<String,Object> map = new HashMap<>();
8        map.put("errorCode","101");
9        map.put("errorMsg","系统错误");
10        return map;
11    }
12}
13

2. 抛出异常的映射类


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1@RestController // 声明 Rest 风格控制器
2@RequestMapping("user")
3public class UserController {
4    @RequestMapping("{age}")
5    @ResponseBody
6    public User getUser(@PathVariable("age")int age ){
7        User user = new User("张三",age);
8        int i =  12/0;
9        return user;
10    }
11
12    @RequestMapping("{name}/{age}")
13    @ResponseBody
14    public User getUser1(@PathVariable("name") String name,@PathVariable("age") int age){
15        User user = new User(name,age);
16        return user;
17    }
18}
19

3. 启动类


1
2
3
4
5
6
7
8
9
1@EnableAutoConfiguration
2@ComponentScan(basePackages = {"com.zth.controller", "com.zth.exception"})
3public class App {
4    public static void main(String[] args){
5        // 启动 SpirngBoot 项目
6        SpringApplication.run(App.class,args);
7    }
8}
9

@ComponentScan(basePackages = {"com.zth.controller", "com.zth.exception"})  扫描异常类

4. 执行结果:

SpringBoot——全局捕获异常

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ 用libcurl库进行http通讯网络编程

2022-1-11 12:36:11

安全资讯

酷派新机外观曝光:乐视经典“大白”脸重现

2016-12-23 14:03:48

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索