Custom errors thrown from server actions are converted to generic Error
Answered
Zenaida Dove posted this in #help-forum
Zenaida DoveOP
When I throw a custom error in my server action, the client sees it as a normal Error:
export class MyCustomError extends Error {
constructor(message: string) {
super(message);
this.name = 'MyCustomError';
// Object.setPrototypeOf(this, MyCustomError.prototype);
}
}'use server'
export async function someServerAction() {
throw new MyCustomError('blah blah blah')
}try {
someServerAction()
} catch (err) {
console.log(err instance of MyCustomError) // false
console.log(err.name) // 'Error'
console.log(err instance of Error) // true
}Answered by joulev
Yeah… well, as long as you don’t throw anything inside the server action, you are good to go.
6 Replies
Zenaida DoveOP
Thank you so much! let me try it.
Zenaida DoveOP
Well, I was looking for a way to throw custom errors from my server actions so I can catch them with instanceof in client
If the only way is to return a normal response that includes the error message, then is this pattern good?:
try {
const res = await callServerAction()
if (res.error) {
throw new Error(res.error.message)
}
// ... rest of function
} catch (err) {
alert('unexpected error', err.message)
}using try/catch for unexpected errors, and throw an error for expected errors, and show an alert or a toast or whatever for both of them
@Zenaida Dove If the only way is to return a normal response that includes the error message, then is this pattern good?:
js
try {
const res = await callServerAction()
if (res.error) {
throw new Error(res.error.message)
}
// ... rest of function
} catch (err) {
alert('unexpected error', err.message)
}
Yeah… well, as long as you don’t throw anything inside the server action, you are good to go.
Answer