Skip to content

Commit

Permalink
Merge pull request #844 from autonomys/feat/improveErrorHandling
Browse files Browse the repository at this point in the history
Improve error handling
  • Loading branch information
marc-aurele-besner authored Sep 6, 2024
2 parents 96cdbad + 63d6b71 commit 3a6eda0
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 11 deletions.
40 changes: 40 additions & 0 deletions explorer/src/app/api/log/[...params]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from 'next/server'
import { sendSlackMessage } from 'utils/slack'

export const POST = async (req: NextRequest) => {
try {
const logData = await req.json()
const slackMessage = await sendSlackMessage('Astral Error', [
{
type: 'header',
text: {
type: 'plain_text',
text: 'Astral Error',
},
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Path: ${req.nextUrl.pathname}`,
},
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `\`\`\`${JSON.stringify(logData, null, 2).slice(0, 25000)}\`\`\``,
},
},
])

if (slackMessage) {
return NextResponse.json({ message: 'Log sent successfully' })
} else {
return NextResponse.json({ error: 'Failed to send log' }, { status: 500 })
}
} catch (error) {
console.error('Error sending log:')
return NextResponse.json({ error: 'Failed to send log' }, { status: 500 })
}
}
9 changes: 7 additions & 2 deletions explorer/src/components/Staking/ActionsModal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use client'

import { WalletType } from '@/constants'
import {
deregisterOperator,
nominateOperator,
Expand All @@ -11,12 +10,15 @@ import {
import { sendGAEvent } from '@next/third-parties/google'
import { Modal } from 'components/common/Modal'
import { TOKEN } from 'constants/general'
import { WalletType } from 'constants/wallet'
import { Field, FieldArray, Form, Formik, FormikState } from 'formik'
import { useTxHelper } from 'hooks/useTxHelper'
import useWallet from 'hooks/useWallet'
import { usePathname } from 'next/navigation'
import Slider from 'rc-slider'
import 'rc-slider/assets/index.css'
import { FC, useCallback, useEffect, useMemo, useState } from 'react'
import { logTx } from 'utils/log'
import { floatToStringWithDecimals, formatUnitsToNumber } from 'utils/number'
import * as Yup from 'yup'

Expand Down Expand Up @@ -61,6 +63,7 @@ export const ActionsModal: FC<Props> = ({ isOpen, action, onClose }) => {
const [walletBalance, setWalletBalance] = useState<number>(0)
const [sliderValue, setSliderValue] = useState(0)
const { handleTxError, sendAndSaveTx } = useTxHelper()
const pathname = usePathname()

const initialValues: FormValues = useMemo(
() => ({
Expand Down Expand Up @@ -138,7 +141,7 @@ export const ActionsModal: FC<Props> = ({ isOpen, action, onClose }) => {
operatorId,
amountToStake,
})
await sendAndSaveTx({
const hash = await sendAndSaveTx({
call: 'nominateOperator',
tx,
signer: injector.signer,
Expand All @@ -148,6 +151,7 @@ export const ActionsModal: FC<Props> = ({ isOpen, action, onClose }) => {
value: `operatorID:${action.operatorId.toString()}`,
})
resetForm()
if (hash) await logTx(pathname, hash.toString(), 'nominateOperator')
handleClose()
} catch (error) {
handleTxError(
Expand All @@ -164,6 +168,7 @@ export const ActionsModal: FC<Props> = ({ isOpen, action, onClose }) => {
action.operatorId,
tokenDecimals,
sendAndSaveTx,
pathname,
handleClose,
handleTxError,
],
Expand Down
6 changes: 3 additions & 3 deletions explorer/src/components/layout/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'use client'

import Footer from '@/components/layout/Footer'
import { CookieBanner } from 'components/common/CookieBanner'
import { ErrorFallback } from 'components/common/ErrorFallback'
import { useOutOfSyncBanner } from 'components/common/OutOfSyncBanner'
import { Container } from 'components/layout/Container'
import Footer from 'components/layout/Footer'
import { SectionHeader } from 'components/layout/SectionHeader'
import { usePathname } from 'next/navigation'
import { FC, ReactNode, useEffect } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import ReactGA from 'react-ga4'
import { logError } from 'utils/log'

type Props = {
children?: ReactNode
Expand All @@ -33,8 +34,7 @@ export const MainLayout: FC<Props> = ({ children, subHeader }) => {
<ErrorBoundary
fallbackRender={ErrorFallback}
onReset={() => window.location.reload()}
// TODO: consider adding error monitoring
onError={(error) => console.error(error)}
onError={async (error) => await logError(pathname, error)}
>
<Container>{children}</Container>
</ErrorBoundary>
Expand Down
18 changes: 12 additions & 6 deletions explorer/src/hooks/useTxHelper.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { TransactionStatus } from '@/constants'
import type { ISubmittableResult, Signer, SubmittableExtrinsic } from '@autonomys/auto-utils'
import { sendGAEvent } from '@next/third-parties/google'
import { TransactionStatus } from 'constants/transaction'
import useChains from 'hooks/useChains'
import useWallet from 'hooks/useWallet'
import { usePathname } from 'next/navigation'
import { useCallback } from 'react'
import toast from 'react-hot-toast'
import { useTransactionsStates } from 'states/transactions'
import { logError, logTx } from 'utils/log'

export interface SendAndSaveTx {
call: string
Expand All @@ -23,14 +25,16 @@ export const useTxHelper = () => {
const { network } = useChains()
const { api, actingAccount, subspaceAccount, injector } = useWallet()
const { addPendingTransactions, getNextNonceForAccount } = useTransactionsStates()
const pathname = usePathname()

const handleTxSuccess = useCallback(
(message: string, call: string, handleSuccess?: (message: string) => void) => {
(txHash: string, message: string, call: string, handleSuccess?: (message: string) => void) => {
handleSuccess ? handleSuccess(message) : console.info('Success', message)
sendGAEvent('event', 'tx_call', { value: call })
toast.success(message, { position: 'bottom-center' })
logTx(pathname, txHash, call)
},
[],
[pathname],
)

const handleTxError = useCallback(
Expand All @@ -39,8 +43,9 @@ export const useTxHelper = () => {
sendGAEvent('event', 'error_message', { value: message })
sendGAEvent('event', 'error', { value: call })
toast.error(message, { position: 'bottom-center' })
logError(pathname, 'call: ' + call)
},
[],
[pathname],
)

const sendAndSaveTx = useCallback(
Expand All @@ -63,6 +68,7 @@ export const useTxHelper = () => {
if (!nonce || txCount > nonce) nonce = txCount
if (nextNonceFromPending > nonce) nonce = nextNonceFromPending
const hash = await tx.signAndSend(from, { nonce, signer })
const txHash = hash.toString()

addPendingTransactions({
ownerAccount: actingAccount,
Expand All @@ -71,15 +77,15 @@ export const useTxHelper = () => {
submittedAtBlockHash: block.block.header.hash.toHex(),
submittedAtBlockNumber: block.block.header.number.toNumber(),
call,
txHash: hash.toString(),
txHash,
blockHash: '',
from,
to: to || from,
amount: amount || '0',
fee: fee || '0',
nonce,
})
handleTxSuccess('The transaction was sent successfully', call)
handleTxSuccess(txHash, 'The transaction was sent successfully', call)

return hash
} catch (e) {
Expand Down
17 changes: 17 additions & 0 deletions explorer/src/utils/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const log = async (type: string, pathname: string, error: Error | string) =>
await fetch(`/api/log/${type}/${pathname}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: typeof error === 'string' ? error : error.message,
stack: typeof error === 'string' ? null : error.stack,
}),
})

export const logError = async (pathname: string, error: Error | string) =>
await log('error', pathname, error)

export const logTx = async (pathname: string, txHash: string, call: string) =>
await log('tx', pathname, 'tx: ' + txHash + ' call: ' + call)

0 comments on commit 3a6eda0

Please sign in to comment.