Next.js & Axios - Forward statusCode 500 from an Axios request to Next.js

Viewed 1265

how can I forward a statusCode from an Axios request to next.js?

Does the error object need to be passed through an axios promise consumer (.catch(error=> { ... })) to next.js? If yes, how? Without the .catch consumer I get the server side error UnhandledPromiseRejectionWarning: Error and Next.js doesn't automatically catch the error to throw a styled error page.

I also overrode the next/error component by adding the custom component to pages/_error.tsx. (Docs - Customizing The Error Page) and it worked before with statucode 404.

import React, { ReactElement } from 'react'

import ErrorPage from '@templates/ErrorPage'
import { PageContext } from '@pages/_app'

interface Props {
  statusCode: number
}

function Error({ statusCode }: Props): ReactElement {
  return <ErrorPage />
}

Error.getInitialProps = ({ res, err }: PageContext) => {
  const errorStatusCode = err ? err.statusCode : 404
  const statusCode = res ? res.statusCode : errorStatusCode

  return { statusCode }
}

export default Error

Furthermore, the request function is written into a helper file, which imports axios.

import axios from 'axios'

export function request(requestObject) {
  const { method, url, data } = requestObject

  ...

  const requestData = { ... }

  ...

  return axios({
    url,
    method,
    data: method !== 'get' ? requestData : null,
    params: method === 'get' ? requestData : null,
  })
    .then(res => {

      ...

      return response
    })
    .catch(
      (error: Error) =>
      {
        throw error
      }
    )
}

Somehow the Next.js's React Error Boundary doesn't catch the statuscode 500 Error.

The entry in the docs to a 500 Page: Link

500 Page

By default Next.js provides a 500 error page that matches the default 404 page’s style. This page is not statically optimized as it allows server-side errors to be reported. This is why 404 and 500 (other errors) are separated.

And yes, I also tried it with a built (production).

Any ideas? Thank you in advance!

0 Answers
Related