Custom error types
Answered
Iridescent shark posted this in #help-forum
Iridescent sharkOP
Hi, after moving my api calls from client side to server side I am unable to receive custom error types. I'm throwing a
new DictionaryError(ErrorType.NotFound)
, but my client side receives it as a regular Error
. Does this have to do with server/client side or am I doing something else wrong?// api.ts
export const getData = async (word: string) => {
// ...
throw new DictionaryError(ErrorType.NotFound);
}
// error.ts
export class DictionaryError extends Error {
public message: string;
constructor(public type: ErrorType) {
super(type);
this.name = "DictionaryError";
this.message = this._getMessage(type);
Object.setPrototypeOf(this, DictionaryError.prototype);
}
private _getMessage(type: ErrorType): string {
// sets the message to "The word you are looking for could not be found."
}
}
// page.tsx:
try {
const res = await getData(word);
} catch (error) {
if (error instanceof DictionaryError) {
// does not run
return;
}
console.log(error.constructor.name); // Error
console.error(error); // has the custom message assigned from ErrorType.NotFound... so it is the right error
}
Answered by Iridescent shark
To fix this, I serialised the error into an object instead and deserialised it on the other side.
1 Reply
Iridescent sharkOP
To fix this, I serialised the error into an object instead and deserialised it on the other side.
Answer