1.统一异常捕获
package com.example.morningrundata.result.handler;
import com.example.morningrundata.result.baseresult.BaseResponse;
import com.example.morningrundata.result.baseresult.ErrorCodeEnum;
import com.example.morningrundata.result.exception.SuperRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* @author:
* @create: 2020/08/20
* @description: 全局异常拦截
*/
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
public class GlobalExceptionHandler {
private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 默认统一异常处理方法
*
* @param e 默认Exception异常对象
* @return
*/
@ExceptionHandler
public BaseResponse superException(HttpServletRequest req, SuperRuntimeException e) {
ErrorCodeEnum errorCodeEnum = ErrorCodeEnum.getErrorCodeEnumByCode(e.getCode());
if (Objects.nonNull(errorCodeEnum)) {
log.warn("Url:{},Method:{}.\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
} else {
log.warn("Url:{},Method:{}.\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
}
return BaseResponse.error().message(e.getMessage()).code(e.getCode());
}
@ExceptionHandler
public BaseResponse exceptionHandler(HttpServletRequest req, Exception e) {
log.error("Url:{},Method:{} .\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
return BaseResponse.error();
}
@ExceptionHandler
public BaseResponse httpMessageNotReadableExceptionHandler(HttpServletRequest req,
HttpMessageNotReadableException e) {
log.warn("Url:{},Method:{} .\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
return BaseResponse.error(ErrorCodeEnum.PARAMETER_FORMAT_ERROR);
}
@ExceptionHandler
public BaseResponse methodArgumentTypeMismatchExceptionHandler(HttpServletRequest req,
MethodArgumentTypeMismatchException e) {
log.warn("Url:{},Method:{} .\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
return BaseResponse.error(ErrorCodeEnum.PARAMETER_FORMAT_ERROR);
}
@ExceptionHandler
public BaseResponse methodHttpMessageConversionExceptionHandler(HttpServletRequest req,
HttpMessageConversionException e) {
log.warn("Url:{},Method:{} .\nController called error!Catch in ErrorHandler", req.getRequestURI(),
req.getMethod(), e);
return BaseResponse.error(ErrorCodeEnum.PARAMETER_FORMAT_ERROR);
}
}
2.全局返回结果
package com.example.morningrundata.result.baseresult;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author:
* @create: 2020/08/28
* @description:
*/
@Data
@NoArgsConstructor
@ApiModel("全局统一返回结果")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BaseResponse<T> {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "数据正文", name = "data")
private T data;
public BaseResponse(T data) {
this.data = data;
this.success = true;
this.code = com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getCode();
this.message = com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getMessage();
}
public BaseResponse success(Boolean success) {
this.success(success);
return this;
}
public BaseResponse message(String message) {
this.setMessage(message);
return this;
}
public BaseResponse code(Integer code) {
this.setCode(code);
return this;
}
public BaseResponse errorCode(String errorCode) {
return this;
}
public static <T> BaseResponse<T> ok() {
BaseResponse<T> r = new BaseResponse<>();
r.setSuccess(true);
r.setCode(com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getCode());
r.setMessage(com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getMessage());
return r;
}
public static <T> BaseResponse<T> ok(T data) {
BaseResponse<T> r = new BaseResponse<>();
r.setSuccess(true);
r.setData(data);
r.setCode(com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getCode());
r.setMessage(com.example.morningrundata.result.baseresult.ErrorCodeEnum.SUCCESS.getMessage());
return r;
}
public static <T> BaseResponse<T> error() {
BaseResponse<T> r = new BaseResponse<>();
r.setSuccess(false);
r.setCode(com.example.morningrundata.result.baseresult.ErrorCodeEnum.UNKNOWN_REASON.getCode());
r.setMessage(com.example.morningrundata.result.baseresult.ErrorCodeEnum.UNKNOWN_REASON.getMessage());
r.setData(null);
return r;
}
public static <T> BaseResponse<T> error(com.example.morningrundata.result.baseresult.ErrorCodeEnum resultCodeEnum) {
BaseResponse<T> r = new BaseResponse<>();
r.setSuccess(false);
r.setCode(resultCodeEnum.getCode());
r.setMessage(resultCodeEnum.getMessage());
r.setData(null);
return r;
}
}
3.错误码提示
package com.example.morningrundata.result.baseresult;
import lombok.Getter;
import lombok.ToString;
import java.util.HashMap;
import java.util.Map;
/**
* @author: xiaoxiangyuan
* @create: 2020/08/28
* @description:
*/
@Getter
@ToString
public enum ErrorCodeEnum {
//
SUCCESS(0, "成功"),
UNKNOWN_REASON(-1, "系统异常,请稍后重试"),
TIME_FORMAT_ERROR(20002, "时间格式错误"),
DATA_CODE_ERROR(20003, "当前时间无打卡记录"),
PARAMETER_FORMAT_ERROR(20004, "参数格式错误"),
CLASS_NAME_ERROR(20005, "当前班级下无打卡数据,请检查同学是否在A点和B点同时打卡"),
DATA_ERROR(20006, "获取数据异常,请联系管理员"),
DATE_ERROR(20007, "仅支持当天6:00-7:00的数据"),
;
private final Integer code;
private final String message;
private static Map<Integer, ErrorCodeEnum> errorCodeEnumMap = new HashMap<>();
static {
for (ErrorCodeEnum value : values()) {
errorCodeEnumMap.put(value.getCode(), value);
}
}
ErrorCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public static ErrorCodeEnum getErrorCodeEnumByCode(Integer code) {
return errorCodeEnumMap.get(code);
}
}
4.统一异常丢出
package com.example.morningrundata.result.exception;
import com.example.morningrundata.result.baseresult.ErrorCodeEnum;
import lombok.Data;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
/**
* @author:
* @create:
* @description:
*/
@Data
public class SuperRuntimeException extends RuntimeException {
/**
* 错误码
*/
private Integer code;
private String message;
/**
* 接受状态码和消息
*
* @param code
* @param message
*/
public SuperRuntimeException(Integer code, String message) {
this.message = message;
this.setCode(code);
}
/**
* 接收枚举类型
*
* @param resultCodeEnum
*/
public SuperRuntimeException(ErrorCodeEnum resultCodeEnum) {
this.message = resultCodeEnum.getMessage();
this.setCode(resultCodeEnum.getCode());
}
public SuperRuntimeException(ErrorCodeEnum resultCodeEnum, String message) {
super(message);
FormattingTuple ft = MessageFormatter.format(resultCodeEnum.getMessage(), message);
this.message = ft.getMessage();
this.setCode(resultCodeEnum.getCode());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118743.html