14

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?

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
  • 2
    Did you make any progress here or can share any resource on how to best handle errors? I am baffled by the frameworks behavior. – Gh05d Jan 08 '21 at 10:04
  • 1
    Have try catch blocks on every API call... try to test each input to getInitialProps or getStaticProps to handle null, error and exception values; these coding practices (albeit very basic) are an important basic step in order to get a reliable working app – Akber Iqbal Jan 08 '21 at 11:24

1 Answers1

1

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) {
    return <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
machineghost
  • 33,529
  • 30
  • 159
  • 234
Pablopvsky
  • 209
  • 2
  • 5