Next.js Discord

Discord Forum

How can I display the error coming from the backend in an error toast using actions?

Answered
(-.-) posted this in #help-forum
Open in Discord
When I build the application, it gives me the following error in my toast: 'An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.' And it doesn't show the error that came from the backend in the toast. I tried using error.tsx but it didn't work. Has anyone encountered this issue?
Answered by joulev
if a server action throws, nextjs and react treat it as an unexpected error (a "devs messed up" situation rather than a "user messed up" situation). if the error is expected, catch it and return an object instead
View full answer

4 Replies

Answer
@(-.-) Like this ? if (!response.ok) { return { message: data.error }; }
Nile Crocodile
That's how I usually do it. Here's how my action functions usually look like, worked great for me so far:
export async function myServerAction() {
  try {
    // throw errors inside of `try` block if something goes wrong, so `catch` block can catch and return it
    if (!auth()) throw new Error('You must be logged in to run this function')

    // ...    
    
    // reached this part of code = everything went well

    return { success: true, message: 'Successfully ran server action' }
  } catch (error: any) {
    console.log('`myServerAction`:', error)
    return { success: false, message: error.message }
  }
}


And then in component where you're calling this function you'd have something like:
import ErrorMessage from '@/components/error-message'
import { myServerAction } from '@/lib/actions'

export async function MyComponent() {
  const response = await myServerAction()

  if (!response.success) return <ErrorMessage message={response.message} />

  return <div className='text-green-500'>{response.message}</div>
}
Thank you for your help