I have a nextjs app sample that sends a request but when trying to catch an error and checking if its my custom type it returns false, and when checking its err.name
returns object
.
page.tsx
'use client'
...some code
handleSumbit() {
try {
const res = await create(values);
console.log(res)
} catch (err: unknown) {
console.log(typeof err, err instanceof ResponseError) <--- returns object, false
if(err instanceof ResponseError) {
if(err.reponse.status === 400) {
// do something with the bad request here
}
}
}
}
...some code
CREATE method Requests.ts
'use server'
export async function create(data: DATA) {
const res = await fetch(`${BASE_URL}/magic`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${acc_tok?.value}`,
},
body: JSON.stringify(data),
});
if (!res.ok) throw new ResponseError('Bad fetch response', res) <---- THE TYPE IM EXPECTING
return await res.json();
}
responseError Class
export class ResponseError extends Error {
response: Response;
constructor(message: string, res: Response) {
super(message);
this.name = this.constructor.name
this.response = res
}
}
I’m not sure if this is the behavior from nextjs but when I tried this in just react (No framework) this works fine, also tried it on the backend this works too. I mean when throwing a custom error I can still verify the type is not changing.