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:
- First I make the request by Axios and get the error it returns if GET is not successful.
- Then I process the information if the data exists
- If there are no I return
error: true
inprops
of the component - 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
}
}
Allow me to ask: the
await Promise.resolve(promiseData)
is really necessary?– Luiz Felipe
He’d return Promise Pending if he hadn’t, right?
– Mateus Queirós
No. The property
data
returned byaxios
is not a promise. Therefore, useawait
there is no need. ThePromise.resolve
is not doing anything either...– Luiz Felipe
Then I can remove that line from the code?
– Mateus Queirós
Yes. You can use
data
straight fromres.data
. :)– Luiz Felipe
Okay. It still works. Thank you.
– Mateus Queirós