feat: added Sentry

close: https://github.com/koreanbots/v2-testing/issues/8
This commit is contained in:
원더 2021-02-03 10:40:01 +09:00
parent b443817633
commit 1aea551d24
4 changed files with 156 additions and 31 deletions

View File

@ -1,6 +1,57 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const SentryWebpackPlugin = require('@sentry/webpack-plugin')
const {
NEXT_PUBLIC_SENTRY_DSN: SENTRY_DSN,
SENTRY_ORG,
SENTRY_PROJECT,
SENTRY_AUTH_TOKEN,
SENTRY_RELEASE,
SOURCE_COMMIT,
SOURCE_BRANCH,
NODE_ENV
} = process.env
const VERSION = require('./package.json').version
const basePath = ''
module.exports = {
images: {
domains: ['cdn.discordapp.com']
env: {
NEXT_PUBLIC_RELEASE_VERSION: VERSION
},
experimental: { scrollRestoration: true }
webpack: (config, options) => {
if(!options.isServer) {
config.resolve.alias['@sentry/node'] = '@sentry/browser'
}
config.plugins.push(
new options.webpack.DefinePlugin({
'process.env.NEXT_IS_SERVER': JSON.stringify(
options.isServer.toString()
),
})
)
if (
SENTRY_DSN &&
SENTRY_ORG &&
SENTRY_PROJECT &&
SENTRY_AUTH_TOKEN &&
SENTRY_RELEASE &&
VERSION &&
NODE_ENV === 'production'
) {
config.plugins.push(
new SentryWebpackPlugin({
include: '.next',
ignore: ['node_modules'],
stripPrefix: ['webpack://_N_E/'],
urlPrefix: `~${basePath}/_next`,
release: `${SENTRY_RELEASE === 'stable' ? VERSION : SOURCE_COMMIT || VERSION}-${SOURCE_BRANCH || SENTRY_RELEASE}`,
})
)
}
return config
},
experimental: { scrollRestoration: true },
basePath
}

View File

@ -3,6 +3,7 @@ import type { AppProps } from 'next/app'
import { ThemeProvider } from 'next-themes'
import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'
import { init } from '@utils/Sentry'
const Footer = dynamic(() => import('@components/Footer'))
const Navbar = dynamic(() => import('@components/Navbar'))
@ -17,7 +18,9 @@ import '../app.css'
import '@fortawesome/fontawesome-free/css/all.css'
import '../github-markdown.css'
export default function App({ Component, pageProps }: AppProps): JSX.Element {
init()
export default function App({ Component, pageProps, err }: KoreanbotsProps): JSX.Element {
const [ betaKey, setBetaKey ] = useState('')
const [ theme, setDefaultTheme ] = useState<string|undefined>(undefined)
let systemColor:string
@ -63,7 +66,7 @@ export default function App({ Component, pageProps }: AppProps): JSX.Element {
<Navbar />
<div className='iu-is-the-best h-full text-black dark:text-gray-100 dark:bg-discord-dark bg-white'>
{
process.env.NEXT_PUBLIC_TESTER_KEY === Crypto.createHmac('sha256', betaKey ?? '').digest('hex') ? <Component {...pageProps} /> : <div className='text-center py-40 px-10'>
process.env.NEXT_PUBLIC_TESTER_KEY === Crypto.createHmac('sha256', betaKey ?? '').digest('hex') ? <Component {...pageProps} err={err} /> : <div className='text-center py-40 px-10'>
<h1 className='text-3xl font-bold'> .</h1><br/>
<input value={betaKey} name='field_name' className='text-black border outline-none px-4 py-2 rounded-2xl' type='text' placeholder='테스터 키' onChange={(e)=> { localStorage.setItem('betaKey', e.target.value); setBetaKey(e.target.value) }} />
</div>
@ -72,4 +75,8 @@ export default function App({ Component, pageProps }: AppProps): JSX.Element {
<Footer />
</ThemeProvider>
)
}
interface KoreanbotsProps extends AppProps {
err: unknown
}

View File

@ -1,33 +1,65 @@
import { NextPage, NextPageContext } from 'next'
import { ErrorText } from '@utils/Constants'
/* https://github.com/vercel/next.js/blob/canary/examples/with-sentry/pages/_error.js */
const CustomError:NextPage<ErrorProps> = ({ statusCode, statusText }) => {
return <div className='h-screen flex flex-col items-center'></div>
}
import { NextPageContext } from 'next'
import NextErrorComponent, { ErrorProps } from 'next/error'
import * as Sentry from '@sentry/node'
export const getServerSideProps = ({ res, err }:NextPageContext) => {
let statusCode:number
// If the res variable is defined it means nextjs
// is in server side
if (res) {
statusCode = res.statusCode
} else if (err) {
// if there is any error in the app it should
// return the status code from here
statusCode = err.statusCode
} else {
// Something really bad/weird happen and status code
// cannot be determined.
statusCode = null
const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
if (!hasGetInitialPropsRun && err) {
// getInitialProps is not called in case of
// https://github.com/vercel/next.js/issues/8592. As a workaround, we pass
// err via _app.js so it can be captured
Sentry.captureException(err)
// Flushing is not required in this case as it only happens on the client
}
const statusText:string = ErrorText[statusCode] ?? ErrorText.DEFAULT
return { props: { statusCode, statusText } }
return <NextErrorComponent statusCode={statusCode} />
}
export default CustomError
MyError.getInitialProps = async ({ res, err, asPath, pathname, query, AppTree }:NextPageContext) => {
const errorInitialProps:CustomErrorProps = await NextErrorComponent.getInitialProps({ err, res, pathname, asPath, query, AppTree })
// Workaround for https://github.com/vercel/next.js/issues/8592, mark when
// getInitialProps has run
errorInitialProps.hasGetInitialPropsRun = true
interface ErrorProps {
statusCode: number
statusText?: string
}
// Running on the server, the response object (`res`) is available.
//
// Next.js will pass an err on the server if a page's data fetching methods
// threw or returned a Promise that rejected
//
// Running on the client (browser), Next.js will provide an err if:
//
// - a page's `getInitialProps` threw or returned a Promise that rejected
// - an exception was thrown somewhere in the React lifecycle (render,
// componentDidMount, etc) that was caught by Next.js's React Error
// Boundary. Read more about what types of exceptions are caught by Error
// Boundaries: https://reactjs.org/docs/error-boundaries.html
if (err) {
Sentry.captureException(err)
// Flushing before returning is necessary if deploying to Vercel, see
// https://vercel.com/docs/platform/limits#streaming-responses
await Sentry.flush(2000)
return errorInitialProps
}
// If this point is reached, getInitialProps was called without any
// information about what the error might be. This is unexpected and may
// indicate a bug introduced in Next.js, so record it in Sentry
Sentry.captureException(
new Error(`_error.js getInitialProps missing data at path: ${asPath}`)
)
await Sentry.flush(2000)
return errorInitialProps
}
interface CustomErrorProps extends ErrorProps {
hasGetInitialPropsRun?: boolean
}
export default MyError

35
utils/Sentry.ts Normal file
View File

@ -0,0 +1,35 @@
import * as Sentry from '@sentry/node'
import { RewriteFrames } from '@sentry/integrations'
export const init = () => {
if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
const integrations = []
if (
process.env.NEXT_IS_SERVER === 'true' &&
process.env.NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR
) {
// For Node.js, rewrite Error.stack to use relative paths, so that source
// maps starting with ~/_next map to files in Error.stack with path
// app:///_next
integrations.push(
new RewriteFrames({
iteratee: (frame) => {
frame.filename = frame.filename.replace(
process.env.NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR,
'app:///'
)
frame.filename = frame.filename.replace('.next', '_next')
return frame
},
})
)
}
Sentry.init({
enabled: process.env.NODE_ENV === 'production',
integrations,
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
release: process.env.NEXT_PUBLIC_RELEASE_VERSION,
})
}
}