全局异常捕获
1.首先创建一个contrller接受test请求
@GetMapping("/test")
public String indexs(@RequestParam("num2")Integer num2){
Integer num3=100/num2;
System.err.println("测试捕获");
return "logintest";
}
2.在创建一个异常类(两种方法可选择,正常应该创建一个类,存放有code和message属性的)
@ControllerAdvice(basePackages = "sumups.login") //这个注解是全局异常扑获,basePackages捕获什么包下的异常
public class ClobaExeption {
//运行出错,返回json字符串
/* @ResponseBody
@ExceptionHandler(RuntimeException.class)// 这个注解简单的说就是把这个普通方法设置为捕获异常的方法
public Map<String,Object> textClobaExption(){
Map<String ,Object> map=new HashMap<>();
map.put("code",500);
return map;
}*/
//返回一个视图
@ExceptionHandler(RuntimeException.class)
public ModelAndView textViewError(){
Map<String ,Object> map=new HashMap<>();
map.put("code",500);
map.put("message","如果进入这个请求,error页面将显示这句话");
//将信息放进modelandviuew
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("date",map);
//返回的视图
modelAndView.setViewName("error");
return modelAndView;
}
}