NextJS best practice for handling "Server Error" and "Client side error"

Viewed 14588

Using NextJS, I see 2 kinds of errors:

Server Error

  • generated it using throw new Error(...) inside getInitialProps...
  • it can occur due to some business logic or unexpected API response;
  • screenshot:

Server error

Unhandled Runtime Error

  • generated it using throw new Error(...) inside a component
  • it can occur due to some business logic;
  • the error here is captured by the ErrorBoundary (which is set inside _app.js)
  • screenshot:

Unhandled Runtime Error

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?

1 Answers

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.

  • If everything is ok 200
  • If does not exist 404
  • If server error 503
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
Related