import { DageResponse } from "./types";

/**
 * 响应错误对象
 */
export class ResponseError extends Error {
  public code: number;
  public response: DageResponse;

  constructor(response: DageResponse) {
    super(response.errorMessage ?? "请求失败");
    this.code = response.errorCode ?? -1;
    this.response = response;
  }
}

/**
 * 判断错误对象是否为响应错误对象。 用于 catch 语句安全地获取 code 和 message
 * @param error
 * @returns
 */
export function isResponseError(error: unknown): error is ResponseError {
  return !!(
    error &&
    typeof error === "object" &&
    "code" in error &&
    "message" in error
  );
}
