@ExceptionHandler 表示拦截异常
@ControllerAdvice controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
1. 定义全局异常类
@ControllerAdvice // 切面
public class GlobalExceptionHandler {
// 捕获运行时异常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<String,Object> exceptionHander(){
Map<String,Object> map = new HashMap<>();
map.put("errorCode","101");
map.put("errorMsg","系统错误");
return map;
}
}
2. 抛出异常的映射类
@RestController // 声明 Rest 风格控制器
@RequestMapping("user")
public class UserController {
@RequestMapping("{age}")
@ResponseBody
public User getUser(@PathVariable("age")int age ){
User user = new User("张三",age);
int i = 12/0;
return user;
}
@RequestMapping("{name}/{age}")
@ResponseBody
public User getUser1(@PathVariable("name") String name,@PathVariable("age") int age){
User user = new User(name,age);
return user;
}
}
3. 启动类
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.zth.controller", "com.zth.exception"})
public class App {
public static void main(String[] args){
// 启动 SpirngBoot 项目
SpringApplication.run(App.class,args);
}
}
@ComponentScan(basePackages = {"com.zth.controller", "com.zth.exception"}) 扫描异常类
4. 执行结果: