1、异常实体类+错误code
public class ErrorInfo<T> {
public static final Integer OK = 0;
public static final Integer ERROR = 100;
private Integer code;
private String messge;
private String url;
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessge() {
return messge;
}
public void setMessge(String messge) {
this.messge = messge;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2、自定义异常类
public class MyException extends Exception{
public MyException(String message){
super(message);
}
}
3、全局异常捕获
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = MyException.class)
@ResponseBody
public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req,MyException e){
ErrorInfo<String> errorInfo = new ErrorInfo<>();
errorInfo.setCode(ErrorInfo.ERROR);
errorInfo.setMessge("show error infomation");
errorInfo.setUrl("www.baidu.com");
errorInfo.setData(req.getRequestURI().toString());
return errorInfo;
}
}
4、具体使用
@RequestMapping(value = "/errorJson",method = RequestMethod.GET)
public String errorJson() throws MyException {
throw new MyException("自定义异常!");
}
5、访问localhost:8080/errorJson