Springboot项目中统一异常处理

Springboot项目中统一异常处理

自定义异常

  1. 自定义异常类代码
@Data //lombok,包含get set 方法
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class ScofieldExecption extends RuntimeException {
    private Integer code; //状态码
    private String message; //异常信息
}
  1. 异常处理Handler类

@ControllerAdvice //全局异常处理器
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class) //捕获异常类型
    @ResponseBody
    public Result error(Exception e)
    {
        e.printStackTrace();
        return Result.error().message("全局异常处理");
    }

    //自定义异常处理
    @ExceptionHandler(ScofieldExecption.class) //捕获异常类型
    @ResponseBody
    public Result error(ScofieldExecption e) 
    {
        e.printStackTrace();
        return Result.error().message(e.getMessage()).code(e.getCode()); //这里Result返回到前端也做成通用类型
    }
}
  1. 统一通用返回类
/**
 * 统一返回前端类,这种写法比较通用
 */
@Data
public class Result {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;
    @ApiModelProperty(value = "返回码")
    private Integer code;
    @ApiModelProperty(value = "返回消息")
    private String message;
    @ApiModelProperty(value = "返回数据")
    private Map<String,Object> data = new HashMap<String,Object>();
    private Result ()
    {
    }
    public static Result ok()
    {
        Result r = new Result();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }
    public static Result error()
    {
        Result r = new Result();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }
    public Result data(String key,Object value){
        this.data.put(key,value);
        return this;
    }
    public Result data(Map<String,Object> map){
        this.setData(map);
        return this;
    }
    public Result code(Integer code)
    {
        this.setCode(code);
        return this;
    }
    public Result success(Boolean success)
    {
        this.setSuccess(success);
        return this;
    }
    public Result message(String message)
    {
        this.setMessage(message);
        return this;
    }
}
  1. 用接口方式设置常量
public interface ResultCode {
    public static Integer SUCCESS = 200; //成功
    public static Integer ERROR = 201; //失败
}

你可能感兴趣的:(springboot,java)