Using NextJS, I see 2 kinds of errors:
Server Error
throw new Error(...)
inside getInitialProps...Unhandled Runtime Error
throw new Error(...)
inside a component_app.js
)Question: unhandled run time errors are captured inside Error Boundary (as they do in ReactJS)... how to best handle the 'server errors'... what is the best practice?
One of the best practices to handle errors is use Early Return, by returning a statusCode
prop inside of the getInitialProps and use that statusCode
to render the error page after render the page to prevent handle the posible errors inside the page.
import Error from "next/error"
function Page({ stars, statusCode}) {
if(statusCode !== 200) {
<Error statusCode={statusCode} />
}
return <div>Next stars: {stars}</div>
}
Page.getInitialProps = async (ctx) => {
try{
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
if(res.status >= 400){
return { stars: json.stargazers_count, statusCode: res.status }
}
return { stars: json.stargazers_count, statusCode: 200 }
} catch(error){
return {stars: null, statusCode: 503}
}
}
export default Page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With