Making a custom error type persist when passed to error.tsx
Unanswered
Chinese Alligator posted this in #help-forum
Chinese AlligatorOP
In my server actions this is the generic function for api calls:
and this is the type of ApiError
I'm trying to pass this to my error.tsx so i can i access the status and message as separate proprieties, but it doesn't persist when passed to the page. When i console log the error i get the message but not an object with the message and status. Also if i console log if error is instance of ApiError i get false.
To clarify: In my error.tsx page the props is of type ({ error }: { error: ApiError })
async function fetchData<T>(
url: string,
accessToken: accessTokenType,
): Promise<T> {
try {
const response = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
const errorResponse = await response.json();
if (errorResponse.error) {
throw new ApiError(
errorResponse.error.status,
errorResponse.error.message,
);
} else {
throw new ApiError(response.status, `An unexpected error occurred.`);
}
}
const data: T = await response.json();
return data;
} catch (error) {
if (error instanceof ApiError) {
throw error; // Re-throw ApiError as is
}
throw new ApiError(500, "An unexpected error occurred");
}
}and this is the type of ApiError
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
if (typeof status !== "number" || typeof message !== "string") {
throw new TypeError("Invalid parameters for ApiError");
}
super(message);
this.status = status;
Object.setPrototypeOf(this, ApiError.prototype);
}
}I'm trying to pass this to my error.tsx so i can i access the status and message as separate proprieties, but it doesn't persist when passed to the page. When i console log the error i get the message but not an object with the message and status. Also if i console log if error is instance of ApiError i get false.
To clarify: In my error.tsx page the props is of type ({ error }: { error: ApiError })
1 Reply
Chinese AlligatorOP
I'm looking to find out if it can be done like this, because I also thought of making the error message show the status and the message itself and get them from there, but i think the first approach is cleaner.