Handle errors in Next.js and Axios

Asked

Viewed 154 times

1

I’m making a Next.js application that uses Axios to make requests. The information I use of the API is coming normally but I would like to handle the returned errors better. Currently my code only returns a 404 error if the request returns any kind of error, but I know that other errors may come and so I would like to make my application more dynamic.

What I’ve tried so far is:

  1. First I make the request by Axios and get the error it returns if GET is not successful.
  2. Then I process the information if the data exists
  3. If there are no I return error: true in props of the component
  4. In the return component the Next.js error if error exist

But this whole process is too long and ends up not returning the error and the message itself. So I’d like to know if there’s a simpler way to deal with the mistakes maybe using something native to the Axios. If anyone can help, I’d appreciate it.

export async function getServerSideProps({ query }) {

    const res = await axios.get(`https://hacker-news.firebaseio.com/v0/user/${query.id}.json?print=pretty`)
        .catch((err) => {
            if (err.response) {
                return err.response
            }
        })
        
    const data = res.data

    if (data) {

        // Processa informações

    } else {
        return {
            props: { data: null, submitted: null, comments: null, error: true }
        }
    }
}

export default function UserPage({ data, submitted, comments, error }) {

    if (!error) {
        return (
            <>
                // Retorna o componente
            </>
        )
    } else {

        return <Error statusCode={404} /> // Erro do Next.js
    }

    
}
  • 1

    Allow me to ask: the await Promise.resolve(promiseData) is really necessary?

  • He’d return Promise Pending if he hadn’t, right?

  • No. The property data returned by axios is not a promise. Therefore, use await there is no need. The Promise.resolve is not doing anything either...

  • Then I can remove that line from the code?

  • Yes. You can use data straight from res.data. :)

  • Okay. It still works. Thank you.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.