自定义状态码枚举
//状态码枚举类
public enum ResCode {
SUCCESS_200(200, "成功"),
FAIL_404(404, "没有数据"),
FAIL_500(500, "服务器错误");
private final Integer code;
private final String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ResCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
自定义响应类
//自定义响应类
@Data
public class Response implements Serializable {
private Integer code;
private String msg;
private Object data;
/**
* 成功回调
*
* @param data
* @return
*/
public static Response success(Object data) {
Response response = new Response();
response.setCode(ResCode.SUCCESS_200.getCode());
response.setMsg(ResCode.SUCCESS_200.getMsg());
response.setData(data);
return response;
}
/**
* 失败回调
*
* @param code
* @param msg
* @return
*/
public static Response fail(Integer code, String msg) {
Response response = new Response();
response.setCode(code);
response.setMsg(msg);
return response;
}
}
自定义异常类
//自定义异常
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomException extends RuntimeException{
private Integer code;
private String msg;
}
全局异常处理
//全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandle {
//自定义异常
@ExceptionHandler(CustomException.class)
public Response customExceptionHandle(CustomException exception) {
return Response.fail(exception.getCode(), exception.getMsg());
}
//其他异常(可在此处记录日志,分析问题)
@ExceptionHandler(Exception.class)
public Response ExceptionHandle() {
return Response.fail(ResCode.FAIL_500.getCode(), ResCode.FAIL_500.getMsg());
}
}