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);
}
}
};