Skip to content

Commit

Permalink
feat: add reason debug for response error toast
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed Sep 10, 2024
1 parent a247e5f commit 7d4260a
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const CopyButton: Component<{
type="button"
onClick={handleCopy}
className={cn(
"center flex text-xs",
"center pointer-events-auto flex text-xs",
"rounded-md border border-accent/5 bg-accent/80 p-1.5 text-white backdrop-blur duration-200",

className,
Expand Down
12 changes: 3 additions & 9 deletions src/renderer/src/components/ui/sonner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,15 @@ import { Toaster as Sonner } from "sonner"

type ToasterProps = React.ComponentProps<typeof Sonner>

const Toaster = ({ ...props }: ToasterProps) => (
export const Toaster = ({ ...props }: ToasterProps) => (
<Sonner
theme={useIsDark() ? "dark" : "light"}
className="toaster group"
toastOptions={{
className: tw`pointer-events-auto`,
classNames: {
toast:
"group toast group-[.toaster]:bg-theme-background group-[.toaster]:text-theme-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-accent group-[.toast]:text-accent-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
content: "min-w-0",
},
}}
{...props}
/>
)

export { Toaster }
54 changes: 54 additions & 0 deletions src/renderer/src/lib/api-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ import { getCsrfToken } from "@hono/auth-js/react"
import PKG from "@pkg"
import { NetworkStatus, setApiStatus } from "@renderer/atoms/network"
import { setLoginModalShow } from "@renderer/atoms/user"
import { CopyButton } from "@renderer/components/ui/code-highlighter"
import { Markdown } from "@renderer/components/ui/markdown"
import { hc } from "hono/client"
import { FetchError, ofetch } from "ofetch"
import { createElement } from "react"
import { toast } from "sonner"
import type { AppType } from "src/hono"


let csrfTokenPromise: Promise<string> | null = null
export const apiFetch = ofetch.create({
baseURL: env.VITE_API_URL,
Expand Down Expand Up @@ -99,3 +104,52 @@ export const getFetchErrorMessage = (error: Error) => {

return error.message
}

export const toastFetchError = (error: Error) => {
let message = ""
let _reason = ""
if (error instanceof FetchError) {
try {
const json = JSON.parse(error.response?._data)

// TODO get the biz code to show the error message, and for i18n
// const bizCode = json.code
const { reason } = json

message = json.message || error.message

if (reason) {
_reason = reason
}
} catch {
message = error.message
}
}

if (!_reason) {
return toast.error(message)
} else {
return toast.error(message, {
duration: 5000,

description: createElement(
"div",
{
className: "min-w-0 flex relative",
},
[
createElement(CopyButton, {
className: "absolute right-0 top-0 z-[1]",
key: "copy",
value: _reason,
}),
createElement(Markdown, {
key: "reason",
className: "text-sm opacity-70 min-w-0",
children: _reason,
}),
],
),
})
}
}
4 changes: 2 additions & 2 deletions src/renderer/src/modules/discover/feed-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Switch } from "@renderer/components/ui/switch"
import { views } from "@renderer/constants"
import { useDeleteSubscription } from "@renderer/hooks/biz/useSubscriptionActions"
import { useAuthQuery } from "@renderer/hooks/common"
import { apiClient, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiClient, getFetchErrorMessage, toastFetchError } from "@renderer/lib/api-fetch"
import { tipcClient } from "@renderer/lib/client"
import { FeedViewType } from "@renderer/lib/enum"
import { getNewIssueUrl } from "@renderer/lib/issues"
Expand Down Expand Up @@ -218,7 +218,7 @@ const FeedInnerForm = ({
onSuccess?.()
},
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
})

Expand Down
5 changes: 2 additions & 3 deletions src/renderer/src/modules/discover/import.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import {
FormMessage,
} from "@renderer/components/ui/form"
import { Input } from "@renderer/components/ui/input"
import { apiFetch, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiFetch, toastFetchError } from "@renderer/lib/api-fetch"
import { cn } from "@renderer/lib/utils"
import type { FeedResponse } from "@renderer/models"
import { Queries } from "@renderer/queries"
import { useMutation } from "@tanstack/react-query"
import { Fragment } from "react/jsx-runtime"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"

import { FollowSummary } from "../../components/feed-summary"
Expand Down Expand Up @@ -80,7 +79,7 @@ export function DiscoverImport() {
Queries.subscription.byView().invalidateRoot()
},
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
})

Expand Down
41 changes: 19 additions & 22 deletions src/renderer/src/modules/discover/recommendations-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { FeedIcon } from "@renderer/components/feed-icon"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@renderer/components/ui/card"
Expand All @@ -28,27 +27,25 @@ export const RecommendationCard: FC<RecommendationCardProps> = memo(({ data, rou
</CardTitle>
</CardHeader>
<CardContent className="p-5 pt-0">
<CardDescription>
<ul className="space-y-1">
{Object.keys(data.routes).map((route) => (
<li
key={route}
className="duration-200 hover:text-theme-foreground-hover"
onClick={() => {
present({
content: () => (
<RecommendationContent routePrefix={routePrefix} route={data.routes[route]} />
),
icon: <FeedIcon className="size-4" size={16} siteUrl={`https://${data.url}`} />,
title: `${data.name} - ${data.routes[route].name}`,
})
}}
>
{data.routes[route].name}
</li>
))}
</ul>
</CardDescription>
<ul className="space-y-1 text-sm text-muted-foreground">
{Object.keys(data.routes).map((route) => (
<li
key={route}
className="duration-200 hover:text-theme-foreground-hover"
onClick={() => {
present({
content: () => (
<RecommendationContent routePrefix={routePrefix} route={data.routes[route]} />
),
icon: <FeedIcon className="size-4" size={16} siteUrl={`https://${data.url}`} />,
title: `${data.name} - ${data.routes[route].name}`,
})
}}
>
{data.routes[route].name}
</li>
))}
</ul>
</CardContent>
</Card>
)
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/src/modules/settings/tabs/invitations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
TooltipTrigger,
} from "@renderer/components/ui/tooltip"
import { useAuthQuery } from "@renderer/hooks/common"
import { apiClient, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiClient, toastFetchError } from "@renderer/lib/api-fetch"
import { usePresentUserProfileModal } from "@renderer/modules/profile/hooks"
import { Queries } from "@renderer/queries"
import { useMutation } from "@tanstack/react-query"
Expand Down Expand Up @@ -143,7 +143,7 @@ const ConfirmModalContent = ({ dismiss }: { dismiss: () => void }) => {
mutationKey: ["newInvitation"],
mutationFn: () => apiClient.invitations.new.$post(),
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
onSuccess(data) {
Queries.invitations.list().invalidate()
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/src/pages/settings/(settings)/actions.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Button } from "@renderer/components/ui/button"
import { useAuthQuery } from "@renderer/hooks/common"
import { apiClient, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiClient, toastFetchError } from "@renderer/lib/api-fetch"
import type {
ActionEntryField,
ActionFeedField,
Expand Down Expand Up @@ -77,7 +77,7 @@ export function Component() {
toast("🎉 Actions saved.")
},
onError: (error) => {
toast.error(getFetchErrorMessage(error))
toastFetchError(error)
},
})

Expand Down
7 changes: 3 additions & 4 deletions src/renderer/src/queries/feed.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { ROUTE_FEED_IN_FOLDER, ROUTE_FEED_PENDING } from "@renderer/constants"
import { useAuthQuery } from "@renderer/hooks/common"
import { apiClient, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiClient, toastFetchError } from "@renderer/lib/api-fetch"
import { defineQuery } from "@renderer/lib/defineQuery"
import { formatXml } from "@renderer/lib/utils"
import type { FeedQueryParams } from "@renderer/store/feed"
import { feedActions } from "@renderer/store/feed"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"

import { entries } from "./entries"

Expand Down Expand Up @@ -52,7 +51,7 @@ export const useClaimFeedMutation = (feedId: string) =>
mutationFn: () => feedActions.claimFeed(feedId),

async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
onSuccess() {
window.posthog?.capture("feed_claimed", {
Expand All @@ -75,6 +74,6 @@ export const useRefreshFeedMutation = (feedId?: string) =>
.invalidateRoot()
},
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
})
6 changes: 3 additions & 3 deletions src/renderer/src/queries/wallet.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useAuthQuery } from "@renderer/hooks/common"
import { apiClient, getFetchErrorMessage } from "@renderer/lib/api-fetch"
import { apiClient, getFetchErrorMessage, toastFetchError } from "@renderer/lib/api-fetch"
import { defineQuery } from "@renderer/lib/defineQuery"
import { useSettingModal } from "@renderer/modules/settings/modal/hooks"
import { useMutation } from "@tanstack/react-query"
Expand Down Expand Up @@ -73,7 +73,7 @@ export const useClaimWalletDailyRewardMutation = () => {
mutationKey: ["claimWalletDailyReward"],
mutationFn: () => apiClient.wallets.transactions.claim_daily.$post(),
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
onSuccess() {
wallet.get().invalidate()
Expand Down Expand Up @@ -105,7 +105,7 @@ export const useWalletTipMutation = () =>
mutationFn: (data: Parameters<typeof apiClient.wallets.transactions.tip.$post>[0]["json"]) =>
apiClient.wallets.transactions.tip.$post({ json: data }),
async onError(err) {
toast.error(getFetchErrorMessage(err))
toastFetchError(err)
},
onSuccess(_, variables) {
wallet.get().invalidate()
Expand Down

0 comments on commit 7d4260a

Please sign in to comment.