springBoot统一异常处理并入库

统一异常处理并错误信息入库

  • 1,我们先建一个统一返回给前端的类Result 包含 success code message  entity
import com.cmp.business.common.enums.ResultCodeEnum;

/**
 * 返回对象
 *
 * @param 
 * @author yusheng
 * @Description TODO
 */
public class Result {
   /**
    * 0失败;1成功
    */
   private String success = "1";

   /**
    * 响应码
    */
   private String code;

   /**
    * 返回信息
    */
   private String message = "";

   /**
    * 返回实体
    */
   private T entity;

   public Result(String success, String message) {
      this.success = success;
      this.message = message;
   }

   public Result(String success, String message, T entity) {
      this.success = success;
      this.message = message;
      this.entity = entity;
   }

   public Result(String success, String code, String message, T entity) {
      this.success = success;
      this.code = code;
      this.message = message;
      this.entity = entity;
   }

   public static  Result build(String code, String msg, U data) {
      return new Result(code, msg, data);
   }

   public static  Result success() {
      return build("1", "success", "");
   }

   public static  Result success(final U data) {
      return new Result("1", ResultCodeEnum.SUCCESS.getCode(), "", data);
   }

   public static Result failure(final String message, final Throwable ex) {
      return new Result("0", ResultCodeEnum.FAILURE.getCode(), message, "");
   }

   public static Result failure(final String message) {
      return new Result("0", ResultCodeEnum.FAILURE.getCode(), message, "");
   }

   public static Result failure(final String code, final String message) {
      return new Result("0", code, message, "");
   }

   public Result() {
      success = "1";
   }


   public String getSuccess() {
      return success;
   }

   public void setSuccess(String success) {
      this.success = success;
   }

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }

   public T getEntity() {
      return entity;
   }

   public void setEntity(T entity) {
      this.entity = entity;
   }

   public String getCode() {
      return code;
   }

   public void setCode(String code) {
      this.code = code;
   }

   public void setFail(String msg) {
      this.success = "0";
      this.message = msg;
   }
}
  •  2,创建一个响应枚举类 ResultCodeEnum
/**
 * 

响应码枚举 - 可参考HTTP状态码的语义

* * @author : yusheng * @description : * @date : 2019/8/22 11:09 */ public enum ResultCodeEnum { SUCCESS("200", "SUCCESS"), FAILURE("400", "FAILURE"), //服务器内部错误 INTERNAL_SERVER_ERROR("10001", "系统异常,操作失败"); private String code; private String desc; ResultCodeEnum(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
  •  3,自定义异常 MyException 需要继承RuntimeException异常
/**
 * 自定义异常类
 */
public class MyException extends RuntimeException {

    /**
     * 异常状态码
     */
    private String code;

    public MyException(Throwable cause) {
        super(cause);
    }

    public MyException(String message) {
        super(message);
    }

    public MyException(String code, String message) {
        super(message);
        this.code = code;
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

    public String getCode() {
        return code;
    }

}
  • 4,建个错误日志表及实体类 error_logs
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

/**
 * @author yusheng
 * @Description:
 */
@Data
@TableName("数据库表名")
@ApiModel(value="错误日志对象", description="")
public class ErrorLogs implements Serializable {

    @ApiModelProperty(value = "主键id")
    @TableField("ID")
    private String id;

    @ApiModelProperty(value = "创建时间")
    @TableField("CREATED_TIME")
    private Date createdTime;

    @ApiModelProperty(value = "错误信息")
    @TableField("ERROR_INFO")
    private String errorInfo;

    @ApiModelProperty(value = "创建人")
    @TableField("CREATED_BY")
    private Long createdBy;

    @ApiModelProperty(value = "状态码")
    @TableField("ERROR_CODE")
    private String errorCode;

    @ApiModelProperty(value = "错误描述")
    @TableField("ERROR_DESC")
    private String errorDesc;
}
  • 5,在错误日志的service层,做错误日志的入库操作
StackTraceElement stackTraceElement = ex.getStackTrace()[0];
//打印日志,错在第几行  取错误信息
String errorInfo = ex.toString() + ",errorMassage:" + stackTraceElement + "," + "errorLine:" + stackTraceElement.getLineNumber();
  • 6,最后写个全局异常处理器类MyGlobalExceptionHandler用@RestControllerAdvice 注解
  • 我们在每一异常捕获的时候,调用service层的错误日志入库操作,这样,就能把每次的错误信息,捕获并入库了。
/**
 * 

全局异常处理器

*/ @RestControllerAdvice public class MyGlobalExceptionHandler { private final static Logger logger = LoggerFactory.getLogger(MyGlobalExceptionHandler.class); @Autowired private ErrorLogsService errorLogsService; /** * 自定义异常处理 */ @ExceptionHandler(value = MyException.class) public Result myException(MyException e) { if (e.getCode() != null) { return Result.failure(e.getCode(), e.getMessage()); } return Result.failure(e.getMessage()); } /** * 1.根异常(用以描述应用程序希望捕获的情况) */ @ExceptionHandler(Exception.class) public Result exception(Exception ex, HttpServletRequest request) { logger.info(ex.getMessage()); errorLogsService.saveErrorLogs(ex, request, 0, ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), ResultCodeEnum.INTERNAL_SERVER_ERROR.getDesc()); return Result.failure(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), ResultCodeEnum.INTERNAL_SERVER_ERROR.getDesc()); } /** * 1.运行时异常(是所有Java虚拟机正常操作期间可以被抛出的异常的父类) */ @ExceptionHandler(RuntimeException.class) public Result handleRuntimeException(RuntimeException ex, HttpServletRequest request) { logger.info(ex.getMessage()); errorLogsService.saveErrorLogs(ex, request, 0, ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), ResultCodeEnum.INTERNAL_SERVER_ERROR.getDesc()); return Result.failure(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), ResultCodeEnum.INTERNAL_SERVER_ERROR.getDesc()); } /** * 2.ValidationException bean校验 */ @ExceptionHandler(ValidationException.class) public Result handleValidationException(ValidationException ex, HttpServletRequest request) { logger.info(ex.getCause().getMessage()); errorLogsService.saveErrorLogs(ex, request, 0, ResultCodeEnum.VALIDATION.getCode(), ResultCodeEnum.VALIDATION.getDesc()); return Result.failure(ResultCodeEnum.VALIDATION.getCode(), ResultCodeEnum.VALIDATION.getDesc()); } .........................等等 } }

你可能感兴趣的:(java)