本文为个人阅读相关资料后的个人笔记:
首先定义json结构
public class JsonResult{ private T data; private String code; private String msg; public JsonResult() { this.code = "0"; this.msg = "操作成功!"; } public JsonResult(String code, String msg) { this.code = code; this.msg = msg; } public JsonResult(T data) { this.data = data; this.code = "0"; this.msg = "操作成功!"; } public JsonResult(T data, String msg) { this.data = data; this.code = "0"; this.msg = msg; } // 省略get和set方法 }
处理异常(以空指针异常为例)
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public JsonResult handleTypeMismatchException(NullPointerException ex) {
logger.error("空指针异常,{}", ex.getMessage());
return new JsonResult("500", "空指针异常了");
}
}
//拦截自定义异常
1.定义异常信息
public enum BusinessMsgEnum {
PARMETER_EXCEPTION("102", "参数异常!"),
SERVICE_TIME_OUT("103", "服务调用超时!"),
PARMETER_BIG_EXCEPTION("102", "输入的图片数量不能超过50张!"),
UNEXPECTED_EXCEPTION("500", "系统发生异常,请联系管理员!");
// 还可以定义更多的业务异常
private String code;
private String msg;
private BusinessMsgEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
// set get方法
}
拦截自定义异常
public class BusinessErrorException extends RuntimeException {
private static final long serialVersionUID = -7480022450501760611L;
private String code;
private String message;
public BusinessErrorException(BusinessMsgEnum businessMsgEnum) {
this.code = businessMsgEnum.code();
this.message = businessMsgEnum.msg();
}
// get set方法
}
处理异常
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BusinessErrorException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public JsonResult handleBusinessError(BusinessErrorException ex) {
String code = ex.getCode();
String message = ex.getMessage();
return new JsonResult(code, message);
}
}
原文链接: link.



