全局异常处理
1.全局异常处理类
@RestControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(Exception.class)
public Object handlerException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
map.put("code",500);
map.put("url",request.getRequestURL());
map.put("msg",e.getMessage());
return map;
}
@ExceptionHandler(GlobalException.class)
public Object handlerException2(GlobalException e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("code",e.getCode());
modelAndView.addObject("msg",e.getMsg());
modelAndView.setViewName("error.html");
return modelAndView;
}
}
2.测试 系统 异常类
@RequestMapping("/exce1")
public Object testExce1(){
int i= 1/0;
return serverUtils;
}
自定义异常处理
1.自定义异常处理类
public class GlobalException extends RuntimeException {
private String code;
private String msg;
public GlobalException(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2. 测试 自定义异常类
@RequestMapping("/exce2")
public Object testExce2(){
throw new GlobalException("5000","查询失败");
}