1.在未配置全局异常之前:访问一个出现异常的接口
@GetMapping("/testJson")
Object testJson(){
int a = 1 /0 ;
return new User("wjl12333",11,"13563986965",new Date(),"10010");
}
浏览器中访问/testJson返回接口如图所示:
2.创建RestExceptonHandler
@RestControllerAdvice
public class RestExceptonHandler {
@ExceptionHandler(Exception.class)
Object handlerRestException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
map.put("code",100);
map.put("msg",e.getMessage());
map.put("url",request.getRequestURL());
return map;
}
}
再次访问/testJson,返回结果如图所示:
3.配置自定义全局异常
创建自定义异常类
/**
* @author LONG
* 自定义全局异常
*/
public class MyException extends RuntimeException {
private String code;
private String msg;
public MyException(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;
}
}
在RestExceptonHandler中添加对自定义异常的处理
@ExceptionHandler(MyException.class)
Object handlerMyException(MyException e, HttpServletRequest request){
//返回跳转的错误提示界面
/* ModelAndView mv = new ModelAndView();
mv.addObject("error.html");
return mv;*/
//返回json数据由前端去判断加载什么页面
logger.error("url {}, msg {}",request.getRequestURL(),e.getMsg());
Map<String,Object> map = new HashMap<>();
map.put("code",e.getCode());
map.put("msg",e.getMsg());
map.put("url",request.getRequestURL());
return map;
}
对自定义异常进行测试
@GetMapping("/testMyException")
Object testMyException(){
throw new MyException("202","我自己定义的异常");
}
返回结果