フロントエンド開発といえば。
react アプリの初期化( pnpm create vite@latest または npm init vite@latest <アプリ名> )

RTK Query mutation の Error型を判別する

type AppQueryError = Extract<
  FetchBaseQueryError,
  { status: number; data: unknown }
>;


/**
 * isFetchBaseQueryError
 */
function isFetchBaseQueryError(
  error: unknown,
): error is FetchBaseQueryError {
  return typeof error === "object" && error != null && "status" in error;
}


/**
 * isRTKQueryError
 */
function isRTKQueryError(
  error: unknown,
): error is FetchBaseQueryError {
  if (typeof error !== "object" || error === null) {
    return false;
  }

  if (!("status" in error)) {
    return false;
  }

  const { status } = error;

  return (
    typeof status === "number" ||
    status === "FETCH_ERROR" ||
    status === "PARSING_ERROR" ||
    status === "TIMEOUT_ERROR" ||
    status === "CUSTOM_ERROR"
  );
}

/**
 * isAppQueryError
 */
function isAppQueryError(
  error: unknown,
): error is AppQueryError {
  return (
    isFetchBaseQueryError(error) &&
    typeof error.status === "number"
  );
}

// isAppQueryError を使う

  const handleClick = async () => {
    try {
      const res = await failMutation().unwrap();  
      console.log("● success", res);
    } catch (er) {
      if (isAppQueryError(er)) {
       // er.status は number型
        console.log("App Error Status:", er.status);
       // er.data は unknown型
        console.log("App Error Data:", er.data);
      }
      else{
        console.log("● RTK Query error", er);
      }
    }
  };
No.2772
08/28 14:52

edit