Created
July 22, 2019 21:00
-
-
Save pedroelsner/b9e48718b27df64eb5ce5daee733cd86 to your computer and use it in GitHub Desktop.
Custom Error page on NextJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import Head from 'next-server/head'; | |
import useElasticApm from '@@/Commons/hooks/useElasticApm'; | |
const statusCodes = { | |
400: 'Bad Request', | |
404: 'This page could not be found', | |
405: 'Method Not Allowed', | |
500: 'Internal Server Error', | |
}; | |
function Error(props) { | |
const { statusCode } = props; | |
useElasticApm({ | |
tags: { | |
error: statusCode, | |
}, | |
}); | |
const title = | |
props.title || | |
statusCodes[statusCode] || | |
'An unexpected error has occurred'; | |
return ( | |
<div> | |
<Head> | |
<title> | |
{statusCode}: {title} | |
</title> | |
</Head> | |
<div> | |
{statusCode ? <h1>{statusCode}</h1> : null} | |
<div> | |
<h2>{title}.</h2> | |
</div> | |
</div> | |
</div> | |
); | |
} | |
Error.getInitialProps = ({ res, err }) => { | |
// eslint-disable-next-line no-nested-ternary | |
const statusCode = res ? res.statusCode : err ? err.statusCode : 404; | |
return { statusCode }; | |
}; | |
Error.defaultProps = { | |
title: null, | |
statusCode: null, | |
}; | |
Error.propTypes = { | |
statusCode: PropTypes.number, | |
title: PropTypes.string, | |
}; | |
export default Error; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment