#Custom errors thrown from server actions are converted to generic Error

8 messages · Page 1 of 1 (latest)

torn temple
#

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
}
thin finchBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

fiery heron
torn temple
#

Thank you so much! let me try it.

torn temple
#

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

fiery heron