Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): normalize HTTP failures as ORPCError (#43950)

Stephen Zhou09fa51d44fc2
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 413e724b5db..a01689ad005 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -91,11 +91,6 @@
"count": 2
}
},
- "web/app/account/(commonLayout)/account-page/email-change-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/app/__tests__/app-detail-loading.spec.tsx": {
"dify/no-app-store-imports": {
"count": 1
@@ -496,11 +491,6 @@
"count": 1
}
},
- "web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts": {
- "@tanstack/query/prefer-query-options": {
- "count": 2
- }
- },
"web/app/components/app/in-site-message/__tests__/notification.spec.tsx": {
"@tanstack/query/prefer-query-options": {
"count": 1
@@ -956,7 +946,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 3
+ "count": 2
}
},
"web/app/components/base/form/components/base/base-form.tsx": {
@@ -1052,7 +1042,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 2
+ "count": 1
}
},
"web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsx": {
@@ -2293,7 +2283,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 2
+ "count": 1
}
},
"web/app/components/rag-pipeline/hooks/use-pipeline-config.ts": {
@@ -2303,7 +2293,7 @@
},
"web/app/components/rag-pipeline/hooks/use-pipeline-init.ts": {
"typescript/no-explicit-any": {
- "count": 2
+ "count": 1
}
},
"web/app/components/rag-pipeline/hooks/use-pipeline-run.ts": {
@@ -2932,7 +2922,7 @@
"count": 7
},
"typescript/no-explicit-any": {
- "count": 5
+ "count": 4
}
},
"web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts": {
@@ -2957,7 +2947,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 22
+ "count": 21
}
},
"web/app/components/workflow/nodes/_base/hooks/use-output-var-list.ts": {
@@ -4341,7 +4331,7 @@
"count": 2
},
"typescript/no-explicit-any": {
- "count": 3
+ "count": 2
}
},
"web/service/common.ts": {
@@ -4629,9 +4619,6 @@
}
},
"web/utils/error-parser.ts": {
- "no-console": {
- "count": 1
- },
"typescript/no-explicit-any": {
"count": 1
}
diff --git a/packages/dify-ui/src/avatar/index.stories.tsx b/packages/dify-ui/src/avatar/index.stories.tsx
index cf6c9c1dee3..9dfe625fe41 100644
--- a/packages/dify-ui/src/avatar/index.stories.tsx
+++ b/packages/dify-ui/src/avatar/index.stories.tsx
@@ -267,9 +267,12 @@ export const Collaborators: Story = {
trigger.focus()
await userEvent.keyboard('{Enter}')
const body = within(canvasElement.ownerDocument.body)
- await expect(await body.findByRole('menuitem', { name: 'Emma' })).toBeVisible()
+ const firstCollaborator = await body.findByRole('menuitem', { name: 'Emma' })
+ await waitFor(() => expect(firstCollaborator).toBeVisible())
+ await waitFor(() => expect(firstCollaborator).toHaveFocus())
await expect(trigger).toHaveAttribute('aria-expanded', 'true')
await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(firstCollaborator).not.toBeVisible())
await waitFor(() => expect(trigger).toHaveFocus())
await expect(trigger).toHaveAttribute('aria-expanded', 'false')
},
diff --git a/packages/dify-ui/src/dropdown-menu/index.stories.tsx b/packages/dify-ui/src/dropdown-menu/index.stories.tsx
index d03f77590f5..a219384d5c3 100644
--- a/packages/dify-ui/src/dropdown-menu/index.stories.tsx
+++ b/packages/dify-ui/src/dropdown-menu/index.stories.tsx
@@ -638,8 +638,17 @@ export const Filterable: Story = {
await userEvent.clear(input)
await userEvent.type(input, 'move')
await expect(body.getByRole('menuitem', { name: 'Move to' })).toBeInTheDocument()
- await userEvent.keyboard('{ArrowDown}{ArrowRight}')
- await expect(await body.findByRole('menuitem', { name: 'Team space' })).toBeInTheDocument()
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('menuitem', { name: 'Move to' })).toHaveAttribute(
+ 'data-highlighted',
+ )
+ })
+ await userEvent.keyboard('{ArrowRight}')
+ const personalSpace = await body.findByRole('menuitem', { name: 'Personal space' })
+ await waitFor(async () => {
+ await expect(personalSpace).toHaveFocus()
+ })
await userEvent.keyboard('{ArrowLeft}')
await waitFor(async () => {
await expect(body.queryByRole('menuitem', { name: 'Team space' })).not.toBeInTheDocument()
@@ -648,7 +657,13 @@ export const Filterable: Story = {
// A filterable submenu focuses its own input and keeps its own query.
await userEvent.clear(input)
await userEvent.type(input, 'share')
- await userEvent.keyboard('{ArrowDown}{ArrowRight}')
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('menuitem', { name: 'Share with' })).toHaveAttribute(
+ 'data-highlighted',
+ )
+ })
+ await userEvent.keyboard('{ArrowRight}')
const submenuInput = await body.findByRole('searchbox', { name: 'Filter teams' })
await waitFor(async () => {
await expect(submenuInput).toHaveFocus()
@@ -663,26 +678,51 @@ export const Filterable: Story = {
})
await expect(input).toHaveValue('share')
await userEvent.keyboard('{ArrowRight}')
- await userEvent.type(await body.findByRole('searchbox', { name: 'Filter teams' }), 'eng')
+ const reopenedSubmenuInput = await body.findByRole('searchbox', { name: 'Filter teams' })
+ await waitFor(async () => {
+ await expect(reopenedSubmenuInput).toHaveFocus()
+ })
+ await userEvent.type(reopenedSubmenuInput, 'eng')
await expect(body.getByRole('menuitem', { name: 'Engineering team' })).toBeInTheDocument()
await expect(body.queryByRole('menuitem', { name: 'Everyone' })).not.toBeInTheDocument()
- await userEvent.keyboard('{ArrowDown}{Enter}')
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('menuitem', { name: 'Engineering team' })).toHaveAttribute(
+ 'data-highlighted',
+ )
+ })
+ await userEvent.keyboard('{Enter}')
await expect(canvas.getByRole('status', { name: 'Last action' })).toHaveTextContent(
'Share with Engineering team',
)
await expect(trigger).toHaveAttribute('aria-expanded', 'false')
+ await waitFor(async () => {
+ await expect(input).not.toBeInTheDocument()
+ })
await userEvent.click(trigger)
const reopenedInput = await body.findByRole('searchbox', { name: 'Filter actions' })
+ await waitFor(async () => {
+ await expect(reopenedInput).toHaveFocus()
+ })
await userEvent.type(reopenedInput, 'zzz')
await expect(await body.findByText('No actions match')).toHaveAttribute('role', 'status')
await userEvent.clear(reopenedInput)
await userEvent.type(reopenedInput, 'rename')
- await userEvent.keyboard('{ArrowDown}{Enter}')
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('menuitem', { name: 'Rename workspace' })).toHaveAttribute(
+ 'data-highlighted',
+ )
+ })
+ await userEvent.keyboard('{Enter}')
await expect(canvas.getByRole('status', { name: 'Last action' })).toHaveTextContent(
'Rename workspace',
)
+ await waitFor(async () => {
+ await expect(reopenedInput).not.toBeInTheDocument()
+ })
await userEvent.click(trigger)
const finalInput = await body.findByRole('searchbox', { name: 'Filter actions' })
diff --git a/packages/dify-ui/src/select/index.stories.tsx b/packages/dify-ui/src/select/index.stories.tsx
index 1aeac930b0a..c9a94e5cb1e 100644
--- a/packages/dify-ui/src/select/index.stories.tsx
+++ b/packages/dify-ui/src/select/index.stories.tsx
@@ -100,12 +100,22 @@ export const Default: Story = {
await expect(body.getByRole('option', { name: 'Tokyo' })).toBeVisible()
})
- await userEvent.keyboard('{ArrowDown}{ArrowDown}{Enter}')
+ const listbox = body.getByRole('listbox')
+ await waitFor(async () => {
+ await expect(body.getByRole('option', { name: 'Seattle' })).toHaveFocus()
+ })
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('option', { name: 'New York' })).toHaveFocus()
+ })
+ await userEvent.keyboard('{ArrowDown}')
+ await waitFor(async () => {
+ await expect(body.getByRole('option', { name: 'Tokyo' })).toHaveFocus()
+ })
+ await userEvent.keyboard('{Enter}')
await expect(trigger).toHaveTextContent('Tokyo')
-
- await userEvent.keyboard('{Escape}')
await waitFor(async () => {
- await expect(body.queryByRole('listbox', { name: 'City options' })).not.toBeInTheDocument()
+ await expect(listbox).not.toBeVisible()
})
},
}
diff --git a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx
index 142754d4ea1..2663b1667a3 100644
--- a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx
+++ b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx
@@ -3,6 +3,7 @@ import type { ReactElement } from 'react'
import { QueryClient, QueryClientProvider, queryOptions, useQuery } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { httpErrorFromResponse } from '@/service/http-error'
const mocks = vi.hoisted(() => ({
queryClient: undefined as QueryClient | undefined,
@@ -265,7 +266,9 @@ describe('CommonLayoutHydrationBoundary', () => {
it('should redirect unauthorized users to the refresh route with the current path', async () => {
mocks.basePath = '/workflow'
mocks.profileQueryFn.mockRejectedValue(
- new Response(JSON.stringify({ code: 'unauthorized' }), { status: 401 }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ code: 'unauthorized' }), { status: 401 }),
+ ),
)
const { CommonLayoutHydrationBoundary } = await import('../hydration-boundary')
@@ -280,7 +283,9 @@ describe('CommonLayoutHydrationBoundary', () => {
mocks.basePath = '/workflow'
mocks.headers.mockResolvedValue(new Headers())
mocks.profileQueryFn.mockRejectedValue(
- new Response(JSON.stringify({ code: 'unauthorized' }), { status: 401 }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ code: 'unauthorized' }), { status: 401 }),
+ ),
)
const { CommonLayoutHydrationBoundary } = await import('../hydration-boundary')
@@ -294,7 +299,9 @@ describe('CommonLayoutHydrationBoundary', () => {
['not_init_validated', '/init'],
])('should use an internal destination for %s errors', async (code, destination) => {
mocks.basePath = '/workflow'
- mocks.profileQueryFn.mockRejectedValue(new Response(JSON.stringify({ code }), { status: 401 }))
+ mocks.profileQueryFn.mockRejectedValue(
+ await httpErrorFromResponse(new Response(JSON.stringify({ code }), { status: 401 })),
+ )
const { CommonLayoutHydrationBoundary } = await import('../hydration-boundary')
await expect(CommonLayoutHydrationBoundary({ children: null })).rejects.toThrow('NEXT_REDIRECT')
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
index c50a13f2223..6eddad07aec 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx
@@ -33,14 +33,6 @@ const render = (ui: Parameters<typeof renderWithConsoleQuery>[0]) =>
vi.mock('@/next/navigation', () => mockNavigation)
-vi.mock('@/service/base', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/base')>()),
- request: async (url: string) => {
- const response = await mockAppResponse(url)
- return response instanceof Response ? response : Response.json(response)
- },
-}))
-
vi.mock('@/context/workspace-state', async () => {
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
return createWorkspaceStateModuleMock(() => mockConsoleState)
@@ -84,6 +76,10 @@ describe('AppDetailLayout', () => {
replace: mockReplace,
})
mockAppResponse.mockResolvedValue(createAppDetail())
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const response = await mockAppResponse(input instanceof Request ? input.url : String(input))
+ return response instanceof Response ? response : Response.json(response)
+ })
useStore.getState().setAppDetail()
})
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
index f401a0dc4a6..32e6279aa35 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
@@ -21,6 +21,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
+import { isNotFoundError } from '@/service/http-error'
import { AppModeEnum } from '@/types/app'
import { getRedirectionPath } from '@/utils/app-redirection'
import { getAppACLCapabilities } from '@/utils/permission'
@@ -30,9 +31,6 @@ type IAppDetailLayoutProps = {
appId: string
}
-const isNotFoundError = (error: unknown) =>
- typeof error === 'object' && error !== null && 'status' in error && error.status === 404
-
const appDetailPageTitle = (pathname: string, t: ReturnType<typeof useTranslation>['t']) => {
if (pathname.endsWith('/workflow') || pathname.endsWith('/configuration'))
return t(($) => $['appMenus.promptEng'], { ns: 'common' })
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
index c2b54e3906c..14f417ca6ab 100644
--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
@@ -1,4 +1,5 @@
import { screen, waitFor } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import { useDatasetDetail } from '@/service/knowledge/use-dataset'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { DatasetACLPermission } from '@/utils/permission'
@@ -188,7 +189,7 @@ describe('DatasetDetailLayout', () => {
// Arrange
mockUseDatasetDetail.mockReturnValue({
data: undefined,
- error: new Response(null, { status }),
+ error: createHttpError(new Response(null, { status })),
refetch: vi.fn(),
} as unknown as ReturnType<typeof useDatasetDetail>)
@@ -206,28 +207,6 @@ describe('DatasetDetailLayout', () => {
expect(screen.queryByText('Pipeline content')).not.toBeInTheDocument()
},
)
-
- it('should redirect when the dataset detail error exposes status without being a Response', async () => {
- // Arrange
- mockUseDatasetDetail.mockReturnValue({
- data: undefined,
- error: { status: 403 },
- refetch: vi.fn(),
- } as unknown as ReturnType<typeof useDatasetDetail>)
-
- // Act
- render(
- <DatasetDetailLayout datasetId="dataset-1">
- <div>Pipeline content</div>
- </DatasetDetailLayout>,
- )
-
- // Assert
- await waitFor(() => {
- expect(mockReplace).toHaveBeenCalledWith('/datasets')
- })
- expect(screen.queryByText('Pipeline content')).not.toBeInTheDocument()
- })
})
describe('Rendering', () => {
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx
index 84dab601d1b..aa434d00f23 100644
--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx
@@ -1,4 +1,5 @@
'use client'
+
import type { FC } from 'react'
import type { DataSet } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
@@ -18,6 +19,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
+import { getHttpErrorStatus } from '@/service/http-error'
import { useDatasetDetail } from '@/service/knowledge/use-dataset'
import { getDatasetACLCapabilities } from '@/utils/permission'
@@ -26,15 +28,8 @@ type IAppDetailLayoutProps = {
datasetId: string
}
-const getResponseStatus = (error: unknown) => {
- if (error instanceof Response) return error.status
-
- if (typeof error === 'object' && error && 'status' in error && typeof error.status === 'number')
- return error.status
-}
-
const shouldRedirectToDatasetList = (error: unknown) => {
- const status = getResponseStatus(error)
+ const status = getHttpErrorStatus(error)
return status === 403 || status === 404
}
diff --git a/web/app/(commonLayout)/error.tsx b/web/app/(commonLayout)/error.tsx
index 79f9f4d5788..86cdfd5287a 100644
--- a/web/app/(commonLayout)/error.tsx
+++ b/web/app/(commonLayout)/error.tsx
@@ -4,7 +4,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { useQueryErrorResetBoundary } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { FullScreenLoading } from '@/app/components/full-screen-loading'
-import { isLegacyBase401 } from '@/features/account-profile/client'
+import { isUnauthorizedError } from '@/service/http-error'
type Props = Readonly<{
error: Error & { digest?: string }
@@ -21,7 +21,7 @@ export default function CommonLayoutError({ error, retry }: Props) {
// until the browser navigation completes, matching main's Splash behavior.
// Showing the "Try again" button here would just flash for a few frames before
// the page navigates away, and clicking it would 401 again anyway.
- if (isLegacyBase401(error)) return <FullScreenLoading />
+ if (isUnauthorizedError(error)) return <FullScreenLoading />
return (
<div className="flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 bg-background-body">
diff --git a/web/app/(commonLayout)/hydration-boundary.tsx b/web/app/(commonLayout)/hydration-boundary.tsx
index 1734d6c2243..08c52c25797 100644
--- a/web/app/(commonLayout)/hydration-boundary.tsx
+++ b/web/app/(commonLayout)/hydration-boundary.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react'
+import { ORPCError } from '@orpc/client'
import { dehydrate, HydrationBoundary, noop } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { serverUserProfileQueryOptions } from '@/features/account-profile/server'
@@ -12,22 +13,6 @@ const CURRENT_SEARCH_HEADER = 'x-dify-search'
const ACCOUNT_PROFILE_PATH = '/account/profile'
const AUTH_REFRESH_PATH = '/auth/refresh'
-type ConsoleErrorPayload = {
- code?: string
-}
-
-const isConsoleErrorPayload = (value: unknown): value is ConsoleErrorPayload =>
- Boolean(value) && typeof value === 'object' && !Array.isArray(value)
-
-const parseConsoleErrorPayload = async (error: Response): Promise<ConsoleErrorPayload | null> => {
- try {
- const payload: unknown = await error.clone().json()
- return isConsoleErrorPayload(payload) ? payload : null
- } catch {
- return null
- }
-}
-
const getCurrentPath = async () => {
const requestHeaders = await headers()
const pathname = requestHeaders.get(CURRENT_PATHNAME_HEADER) || '/'
@@ -41,11 +26,10 @@ const redirectToAuthRefresh = async () => {
}
const handleProfileError = async (error: unknown) => {
- if (!(error instanceof Response)) throw error
+ if (!(error instanceof ORPCError)) throw error
- const errorData = await parseConsoleErrorPayload(error)
- if (errorData?.code === 'not_setup') redirect('/install')
- if (errorData?.code === 'not_init_validated') redirect('/init')
+ if (error.code === 'not_setup') redirect('/install')
+ if (error.code === 'not_init_validated') redirect('/init')
if (error.status === 401) await redirectToAuthRefresh()
throw error
diff --git a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
index 4ea39a7a665..10d415ff876 100644
--- a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
@@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import useDocumentTitle from '@/hooks/use-document-title'
+import { createHttpError } from '@/service/http-error'
import { TransferMethod } from '@/types/app'
import FormContent from '../form'
import { useFormSubmit } from '../use-form-submit'
@@ -211,21 +212,27 @@ describe('Human input share form', () => {
it('should render status cards for terminal fetch states', () => {
const cases = [
{
- error: { code: 'human_input_form_expired' },
+ error: createHttpError(new Response(null, { status: 400 }), {
+ code: 'human_input_form_expired',
+ }),
title: 'share.humanInput.sorry',
subtitle: 'share.humanInput.expired',
documentTitle: 'share.humanInput.expired',
submissionID: true,
},
{
- error: { code: 'human_input_form_submitted' },
+ error: createHttpError(new Response(null, { status: 400 }), {
+ code: 'human_input_form_submitted',
+ }),
title: 'share.humanInput.sorry',
subtitle: 'share.humanInput.completed',
documentTitle: 'share.humanInput.completed',
submissionID: true,
},
{
- error: { code: 'web_form_rate_limit_exceeded' },
+ error: createHttpError(new Response(null, { status: 400 }), {
+ code: 'web_form_rate_limit_exceeded',
+ }),
title: 'share.humanInput.rateLimitExceeded',
subtitle: undefined,
documentTitle: 'share.humanInput.rateLimitExceeded',
diff --git a/web/app/(humanInputLayout)/form/[token]/form.tsx b/web/app/(humanInputLayout)/form/[token]/form.tsx
index 3de4b011925..7f1e7e3a0ec 100644
--- a/web/app/(humanInputLayout)/form/[token]/form.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/form.tsx
@@ -1,8 +1,9 @@
'use client'
+
import type { FormInputItem, UserAction } from '@/app/components/workflow/nodes/human-input/types'
import type { CustomConfigValueType, SiteInfo } from '@/models/share'
-import type { HumanInputFormError } from '@/service/use-share'
import type { HumanInputResolvedValue } from '@/types/workflow'
+import { ORPCError } from '@orpc/client'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
@@ -39,10 +40,10 @@ const FormContent = () => {
? formData.site.custom_config.replace_webapp_logo
: null
- const expired = (error as HumanInputFormError | null)?.code === 'human_input_form_expired'
- const submitted = (error as HumanInputFormError | null)?.code === 'human_input_form_submitted'
- const rateLimitExceeded =
- (error as HumanInputFormError | null)?.code === 'web_form_rate_limit_exceeded'
+ const errorCode = error instanceof ORPCError ? error.code : undefined
+ const expired = errorCode === 'human_input_form_expired'
+ const submitted = errorCode === 'human_input_form_submitted'
+ const rateLimitExceeded = errorCode === 'web_form_rate_limit_exceeded'
const documentTitle = isLoading
? t(($) => $.loading, { ns: 'common' })
: success
diff --git a/web/app/(shareLayout)/components/__tests__/splash.spec.tsx b/web/app/(shareLayout)/components/__tests__/splash.spec.tsx
index c9b5582b030..f1f70568e98 100644
--- a/web/app/(shareLayout)/components/__tests__/splash.spec.tsx
+++ b/web/app/(shareLayout)/components/__tests__/splash.spec.tsx
@@ -1,4 +1,5 @@
import { render, screen, waitFor } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import Splash from '../splash'
const navigationMocks = vi.hoisted(() => ({
@@ -131,7 +132,7 @@ describe('Splash', () => {
userLoggedIn: true,
appLoggedIn: false,
})
- fetchAccessTokenMock.mockRejectedValue(new Response(null, { status: 404 }))
+ fetchAccessTokenMock.mockRejectedValue(createHttpError(new Response(null, { status: 404 })))
render(
<Splash>
@@ -177,7 +178,7 @@ describe('Splash', () => {
userLoggedIn: true,
appLoggedIn: false,
})
- fetchAccessTokenMock.mockRejectedValue(new Response(null, { status: 401 }))
+ fetchAccessTokenMock.mockRejectedValue(createHttpError(new Response(null, { status: 401 })))
render(
<Splash>
diff --git a/web/app/(shareLayout)/components/splash.tsx b/web/app/(shareLayout)/components/splash.tsx
index c9b221b60bb..687c29f9191 100644
--- a/web/app/(shareLayout)/components/splash.tsx
+++ b/web/app/(shareLayout)/components/splash.tsx
@@ -1,4 +1,5 @@
'use client'
+
import type { PropsWithChildren } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -12,6 +13,7 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useWebAppStore } from '@/context/web-app-context'
import { AccessMode } from '@/models/access-control'
import { usePathname, useRouter, useSearchParams } from '@/next/navigation'
+import { getHttpErrorStatus, isNotFoundError } from '@/service/http-error'
import { fetchAccessToken } from '@/service/share'
import { resolveWebAppAddress } from '@/service/webapp-address'
import {
@@ -121,13 +123,13 @@ function Splash({ children }: PropsWithChildren) {
setWebAppPassport(address, access_token)
redirectOrFinish()
} catch (error) {
- if (error instanceof Response && error.status === 404) {
+ if (isNotFoundError(error)) {
setUnavailableShareCode(effectiveShareCode)
await webAppLogout(address)
return
}
await webAppLogout(address)
- proceedToAuth(error instanceof Response && error.status === 401)
+ proceedToAuth(getHttpErrorStatus(error) === 401)
}
}
})()
diff --git a/web/app/__tests__/error.spec.tsx b/web/app/__tests__/error.spec.tsx
index db99e79fc12..c12f5b541c6 100644
--- a/web/app/__tests__/error.spec.tsx
+++ b/web/app/__tests__/error.spec.tsx
@@ -1,30 +1,35 @@
-import { QueryErrorResetBoundary } from '@tanstack/react-query'
+import { ORPCError } from '@orpc/client'
+import { QueryClient, QueryErrorResetBoundary } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vite-plus/test'
import CommonLayoutError from '@/app/(commonLayout)/error'
import AppError from '@/app/error'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
+
+const refresh = vi.hoisted(() => vi.fn())
+vi.mock('@/service/refresh-token', () => ({ refreshAccessTokenOrReLogin: refresh }))
type ErrorRecoveryProps = Readonly<{
+ error: Error
retry: () => void
}>
const routeErrors = [
{
name: 'root error',
- renderError: (props: ErrorRecoveryProps) => <AppError error={new Error('failed')} {...props} />,
+ renderError: (props: ErrorRecoveryProps) => <AppError {...props} />,
},
{
name: 'common layout error',
- renderError: (props: ErrorRecoveryProps) => (
- <CommonLayoutError error={new Error('failed')} {...props} />
- ),
+ renderError: (props: ErrorRecoveryProps) => <CommonLayoutError {...props} />,
},
]
describe('route error recovery', () => {
afterEach(() => {
vi.restoreAllMocks()
+ refresh.mockReset()
})
it.each(routeErrors)(
@@ -38,6 +43,7 @@ describe('route error recovery', () => {
<QueryErrorResetBoundary>
{({ isReset }) =>
renderError({
+ error: new Error('failed'),
retry: () => retry(isReset()),
})
}
@@ -49,4 +55,38 @@ describe('route error recovery', () => {
expect(retry).toHaveBeenCalledWith(true)
},
)
+
+ it.each(routeErrors)(
+ 'keeps the $name recoverable when token refresh is temporarily unavailable',
+ async ({ renderError }) => {
+ const user = userEvent.setup()
+ const retry = vi.fn()
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ window.history.replaceState({}, '', '/apps')
+ const initialUrl = window.location.href
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
+ Response.json({ code: 'unauthorized', message: 'Expired access token' }, { status: 401 }),
+ )
+ const refreshError = new ORPCError('HTTP_ERROR', { status: 503 })
+ refresh.mockRejectedValue(refreshError)
+ const queryClient = new QueryClient()
+
+ const error: unknown = await queryClient
+ .query({ ...userProfileQueryOptions(), retryDelay: 0 })
+ .catch((error: unknown) => error)
+
+ expect(refresh).toHaveBeenCalledTimes(4)
+ expect(window.location.href).toBe(initialUrl)
+ if (!(error instanceof Error)) throw new Error('Expected a profile request failure')
+ render(
+ <QueryErrorResetBoundary>
+ {({ isReset }) => renderError({ error, retry: () => retry(isReset()) })}
+ </QueryErrorResetBoundary>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.errorBoundary.tryAgain' }))
+ expect(retry).toHaveBeenCalledWith(true)
+ queryClient.clear()
+ },
+ )
})
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
index 1a1f43c56b6..7e6c2ceaa03 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
@@ -1,10 +1,16 @@
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { toast } from '@/app/notifications'
import { checkEmailExisted, resetEmail, sendVerifyCode, verifyEmail } from '@/service/common'
+import { createHttpError } from '@/service/http-error'
import EmailChangeModal from '../email-change-modal'
const mockLogout = vi.fn()
+vi.mock('@/app/notifications', () => ({
+ toast: { error: vi.fn() },
+}))
+
vi.mock('@/service/common', () => ({
checkEmailExisted: vi.fn(),
resetEmail: vi.fn(),
@@ -77,10 +83,9 @@ describe('EmailChangeModal', () => {
})
it('associates an unavailable-email error and clears it when the user edits the address', async () => {
- vi.mocked(checkEmailExisted).mockRejectedValue({
- status: 400,
- json: async () => ({ code: 'email_already_in_use' }),
- })
+ vi.mocked(checkEmailExisted).mockRejectedValue(
+ createHttpError(new Response(null, { status: 400 }), { code: 'email_already_in_use' }),
+ )
const user = userEvent.setup()
render(<EmailChangeModal email="[email protected]" onClose={vi.fn()} />)
@@ -105,4 +110,70 @@ describe('EmailChangeModal', () => {
screen.queryByText('accountSettings.account.changeEmail.existingEmail'),
).not.toBeInTheDocument()
})
+
+ it('shows the server message when sending a verification code fails', async () => {
+ vi.mocked(sendVerifyCode).mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 429 }), {
+ code: 'rate_limit_exceeded',
+ message: 'Try again in one minute',
+ }),
+ )
+ const user = userEvent.setup()
+ render(<EmailChangeModal email="[email protected]" onClose={vi.fn()} />)
+
+ await user.click(
+ screen.getByRole('button', { name: 'accountSettings.account.changeEmail.sendVerifyCode' }),
+ )
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Error sending verification code: Try again in one minute',
+ ),
+ )
+ expect(verifyEmail).not.toHaveBeenCalled()
+ expect(mockLogout).not.toHaveBeenCalled()
+ })
+
+ it('preserves the verification step after an HTTP error and allows another attempt', async () => {
+ vi.mocked(verifyEmail).mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'invalid_code',
+ message: 'Verification code has expired',
+ }),
+ )
+ const user = userEvent.setup()
+ render(<EmailChangeModal email="[email protected]" onClose={vi.fn()} />)
+
+ await user.click(
+ screen.getByRole('button', { name: 'accountSettings.account.changeEmail.sendVerifyCode' }),
+ )
+ const originCode = await screen.findByRole('textbox', {
+ name: 'accountSettings.account.changeEmail.codeLabel',
+ })
+ await user.type(originCode, '123456{Enter}')
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Error verifying email: Verification code has expired',
+ ),
+ )
+ expect(originCode).toBeVisible()
+ expect(
+ screen.queryByRole('textbox', { name: 'accountSettings.account.changeEmail.emailLabel' }),
+ ).not.toBeInTheDocument()
+ expect(resetEmail).not.toHaveBeenCalled()
+
+ await user.type(originCode, '654321{Enter}')
+
+ expect(
+ await screen.findByRole('textbox', {
+ name: 'accountSettings.account.changeEmail.emailLabel',
+ }),
+ ).toBeVisible()
+ expect(verifyEmail).toHaveBeenLastCalledWith({
+ email: '[email protected]',
+ code: '654321',
+ token: 'email-token',
+ })
+ })
})
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
index 8d3a19fdc63..e45263b9bf7 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
import { toast } from '@/app/notifications'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { consoleQuery } from '@/service/console'
+import { httpErrorFromResponse } from '@/service/http-error'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
import AccountPage from '../index'
@@ -378,13 +379,18 @@ describe('AccountPage', () => {
it.each(['name', 'password'])(
'leaves a server-reported %s failure to the request layer',
async (field) => {
- // The request layer reports the server message and rejects with the Response.
+ // The request layer reports the server message and rejects with an ORPCError.
const error = vi.spyOn(toast, 'error')
const user = userEvent.setup()
mocks.request.mockRejectedValueOnce(
- new Response(JSON.stringify({ code: 'invalid_param', message: 'Rejected', status: 400 }), {
- status: 400,
- }),
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({ code: 'invalid_param', message: 'Rejected', status: 400 }),
+ {
+ status: 400,
+ },
+ ),
+ ),
)
renderPage({ isPasswordSet: true })
diff --git a/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx b/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx
index 727cd5a0fdf..7e70c32db25 100644
--- a/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx
+++ b/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx
@@ -14,6 +14,7 @@ import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
+import { ORPCError } from '@orpc/client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -169,9 +170,10 @@ export function ChangePasswordDialog({ isPasswordSet }: { isPasswordSet: boolean
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
actionsRef.current?.close()
} catch (error) {
- // The request layer already reports every error the server answered with.
+ // HTTP error notifications are owned by the request layer.
// Only report a failure that never produced a response.
- if (error instanceof Error && error.message) toast.error(error.message)
+ if (!(error instanceof ORPCError) && error instanceof Error && error.message)
+ toast.error(error.message)
}
}
diff --git a/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx b/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx
index f4afdecd5bb..dc822127233 100644
--- a/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx
+++ b/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx
@@ -11,6 +11,7 @@ import {
} from '@langgenius/dify-ui/dialog'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
+import { ORPCError } from '@orpc/client'
import { useMutation } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -70,9 +71,10 @@ export function EditAccountNameDialog({ name }: { name: string }) {
await updateProfile.mutateAsync({ body: { name } })
actionsRef.current?.close()
} catch (error) {
- // The request layer already reports every error the server answered with.
+ // HTTP error notifications are owned by the request layer.
// Only report a failure that never produced a response.
- if (error instanceof Error && error.message) toast.error(error.message)
+ if (!(error instanceof ORPCError) && error instanceof Error && error.message)
+ toast.error(error.message)
}
}
diff --git a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
index 653ffe8af13..5eef71289d9 100644
--- a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
+++ b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
@@ -1,9 +1,9 @@
-import type { ResponseError } from '@/service/fetch'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
+import { ORPCError } from '@orpc/client'
import { RiCloseLine } from '@remixicon/react'
import { useDebounceFn } from 'ahooks'
import { useCallback, useEffect, useRef, useState } from 'react'
@@ -11,7 +11,7 @@ import { Trans, useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { checkEmailExisted, resetEmail, sendVerifyCode, verifyEmail } from '@/service/common'
import { useLogout } from '@/service/use-common'
-import { asyncRunSafe } from '@/utils'
+import { getErrorMessage } from '@/utils/error-message'
type Props = {
onClose: () => void
@@ -29,27 +29,6 @@ type Step = (typeof STEP)[keyof typeof STEP]
const emailPattern = /^[\w.!#$%&'*+\-/=?^`{|}~]+@(?:[\w-]+\.)+[\w-]{2,}$/
-type FetchResponseError = {
- status: number
- json: () => Promise<ResponseError>
-}
-
-function getErrorMessage(error: unknown) {
- if (error instanceof Error) return error.message
- if (typeof error === 'object' && error !== null && 'message' in error) {
- const message = (error as { message?: unknown }).message
- return typeof message === 'string' ? message : ''
- }
- return ''
-}
-
-function isFetchResponseError(error: unknown): error is FetchResponseError {
- if (typeof error !== 'object' || error === null) return false
-
- const maybeError = error as { status?: unknown; json?: unknown }
- return typeof maybeError.status === 'number' && typeof maybeError.json === 'function'
-}
-
const EmailChangeModal = ({ onClose, email }: Props) => {
const { t } = useTranslation(['common', 'accountSettings'])
const [step, setStep] = useState<Step>(STEP.start)
@@ -96,7 +75,7 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
startCount()
if (res.data) setStepToken(res.data)
} catch (error) {
- toast.error(`Error sending verification code: ${getErrorMessage(error)}`)
+ toast.error(`Error sending verification code: ${getErrorMessage(error) ?? ''}`)
}
}
@@ -119,7 +98,7 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
toast.error('Verifying email failed')
}
} catch (error) {
- toast.error(`Error verifying email: ${getErrorMessage(error)}`)
+ toast.error(`Error verifying email: ${getErrorMessage(error) ?? ''}`)
}
}
@@ -148,9 +127,8 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
setUnAvailableEmail(false)
} catch (e: unknown) {
if (latestEmailRef.current !== email) return
- if (isFetchResponseError(e) && e.status === 400) {
- const [, errRespData] = await asyncRunSafe<ResponseError>(e.json())
- const { code } = errRespData || {}
+ if (e instanceof ORPCError && e.status === 400) {
+ const { code } = e
if (code === 'email_already_in_use') setNewEmailExited(true)
if (code === 'account_in_freeze') setUnAvailableEmail(true)
}
@@ -200,7 +178,7 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
})
await logout()
} catch (error) {
- toast.error(`Error changing email: ${getErrorMessage(error)}`)
+ toast.error(`Error changing email: ${getErrorMessage(error) ?? ''}`)
}
}
diff --git a/web/app/account/oauth/authorize/__tests__/page.spec.tsx b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
index 24acf521a8b..27767414710 100644
--- a/web/app/account/oauth/authorize/__tests__/page.spec.tsx
+++ b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { seedSystemFeatures } from '@/test/console/query-data'
import OAuthAuthorize from '../page'
@@ -22,7 +23,7 @@ vi.mock('@/next/navigation', () => ({
vi.mock('@/service/base', () => ({
get: vi.fn(async () => {
- if (!mocks.profileLoggedIn) throw new Response(null, { status: 401 })
+ if (!mocks.profileLoggedIn) throw createHttpError(new Response(null, { status: 401 }))
return new Response(
JSON.stringify({
avatar_url: null,
diff --git a/web/app/account/oauth/authorize/page.tsx b/web/app/account/oauth/authorize/page.tsx
index 2bcf2c00871..852cc7347b6 100644
--- a/web/app/account/oauth/authorize/page.tsx
+++ b/web/app/account/oauth/authorize/page.tsx
@@ -16,11 +16,12 @@ import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { toast } from '@/app/notifications'
-import { isLegacyBase401, userProfileQueryOptions } from '@/features/account-profile/client'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { isUnauthorizedError } from '@/service/http-error'
import { useLogout } from '@/service/use-common'
import { getAvatarInitial } from '@/utils/avatar'
import { buildOAuthCallbackUrl, buildReturnUrl, useSilentAuthorize } from './use-silent-authorize'
@@ -70,7 +71,7 @@ export default function OAuthAuthorize() {
error: profileError,
} = useQuery({
...userProfileQueryOptions(),
- throwOnError: (err) => !isLegacyBase401(err),
+ throwOnError: (err) => !isUnauthorizedError(err),
})
const isLoggedIn = !!userProfileResp && !profileError
const userProfile = userProfileResp?.profile
diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
index 91cf28d2b56..9bfaca9519a 100644
--- a/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
+++ b/web/app/components/app-sidebar/dataset-info/__tests__/dropdown-callbacks.spec.tsx
@@ -3,6 +3,7 @@ import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'
+import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { RETRIEVE_METHOD } from '@/types/app'
import { DatasetACLPermission } from '@/utils/permission'
@@ -269,9 +270,9 @@ describe('Dropdown callback coverage', () => {
it('should surface the backend message when checking app usage fails', async () => {
const user = userEvent.setup()
- mockCheckIsUsedInApp.mockRejectedValueOnce({
- json: vi.fn().mockResolvedValue({ message: 'check failed' }),
- })
+ mockCheckIsUsedInApp.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), { message: 'check failed' }),
+ )
render(<Dropdown expand />)
diff --git a/web/app/components/app-sidebar/dataset-info/dropdown.tsx b/web/app/components/app-sidebar/dataset-info/dropdown.tsx
index 8d32ee552f7..2511a490422 100644
--- a/web/app/components/app-sidebar/dataset-info/dropdown.tsx
+++ b/web/app/components/app-sidebar/dataset-info/dropdown.tsx
@@ -33,6 +33,7 @@ import { datasetDetailQueryKeyPrefix, useInvalidDatasetList } from '@/service/kn
import { useInvalid } from '@/service/use-base'
import { useExportPipelineDSL } from '@/service/use-pipeline'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
import RenameDatasetModal from '../../datasets/rename-modal'
@@ -41,26 +42,6 @@ type DropDownProps = {
triggerClassName?: string
}
-type JsonErrorResponse = {
- json: () => Promise<{ message?: string }>
-}
-
-const isJsonErrorResponse = (error: unknown): error is JsonErrorResponse => {
- return (
- typeof error === 'object' &&
- error !== null &&
- 'json' in error &&
- typeof error.json === 'function'
- )
-}
-
-const getErrorMessage = async (error: unknown) => {
- if (!isJsonErrorResponse(error)) return 'Unknown error'
-
- const res = await error.json()
- return res?.message || 'Unknown error'
-}
-
const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
const { t } = useTranslation(['app', 'common', 'dataset', 'datasetPipeline', 'navigation'])
const { push, replace } = useRouter()
@@ -142,7 +123,7 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
)
setShowConfirmDelete(true)
} catch (e: unknown) {
- toast.error(await getErrorMessage(e))
+ toast.error(getErrorMessage(e) ?? 'Unknown error')
}
}, [dataset.id, t])
diff --git a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
index 3785bfc44c7..d87ce91447b 100644
--- a/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
+++ b/web/app/components/app/__tests__/use-export-app-dsl.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, renderHook, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError, httpErrorFromResponse } from '@/service/http-error'
import AppExportConfirmModal from '../export-confirm-modal'
import { useExportAppDsl, useExportWorkflowAppDsl } from '../use-export-app-dsl'
@@ -117,7 +118,9 @@ describe('useExportAppDsl', () => {
expect(mocks.exportAppDsl).toHaveBeenCalledTimes(1)
await act(async () => {
- rejectExport(new Response(JSON.stringify({ message: 'Skill unavailable' }), { status: 400 }))
+ rejectExport(
+ createHttpError(new Response(null, { status: 400 }), { message: 'Skill unavailable' }),
+ )
})
expect(onClose).not.toHaveBeenCalled()
expect(screen.getByRole('checkbox')).toBeChecked()
@@ -238,14 +241,16 @@ describe('useExportAppDsl', () => {
})
})
- it('keeps the localized fallback when the export response has no readable message', async () => {
- mocks.exportAppDsl.mockRejectedValue(new Response('Bad gateway', { status: 502 }))
+ it('keeps the localized failure title and exposes the HTTP status when the response has no readable message', async () => {
+ mocks.exportAppDsl.mockRejectedValue(
+ await httpErrorFromResponse(new Response('Bad gateway', { status: 502 })),
+ )
const { result } = renderHook(() => useExportAppDsl(), { wrapper: createWrapper() })
await act(async () => {
await result.current.exportAppDsl({ appId: 'app-id', appName: 'App' })
})
expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith('app.exportAppFailed', {
- description: undefined,
+ description: 'HTTP 502',
})
expect(mocks.downloadBlob).not.toHaveBeenCalled()
})
@@ -321,9 +326,11 @@ describe('useExportAppDsl', () => {
'lets the promise toast own %s export errors without triggering a download',
async (format) => {
mocks.exportAppDsl.mockRejectedValue(
- Response.json(
- { message: "Package contains unusable Skill 'news-source-verification'" },
- { status: 500 },
+ await httpErrorFromResponse(
+ Response.json(
+ { message: "Package contains unusable Skill 'news-source-verification'" },
+ { status: 500 },
+ ),
),
)
const { result } = renderHook(() => useExportAppDsl(), { wrapper: createWrapper() })
diff --git a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx
index 0be97cea37e..1f2b648bebf 100644
--- a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactElement } from 'react'
import type { AppModeEnum } from '@/types/app'
import { screen } from '@testing-library/react'
import { consoleQuery } from '@/service/console'
+import { createHttpError } from '@/service/http-error'
import { createQueryClientWrapper } from '@/test/console/query-client'
import { render as renderWithConsole } from '@/test/console/render'
import { createAppDetailFixture } from '@/test/fixtures/app'
@@ -285,8 +286,8 @@ describe('BuiltInAccessPoints', () => {
retry: (failureCount: number, error: unknown) => boolean
}
- expect(options.retry(0, new Response(null, { status: 403 }))).toBe(false)
- expect(options.retry(0, new Response(null, { status: 500 }))).toBe(true)
- expect(options.retry(3, new Response(null, { status: 500 }))).toBe(false)
+ expect(options.retry(0, createHttpError(new Response(null, { status: 403 })))).toBe(false)
+ expect(options.retry(0, createHttpError(new Response(null, { status: 500 })))).toBe(true)
+ expect(options.retry(3, createHttpError(new Response(null, { status: 500 })))).toBe(false)
})
})
diff --git a/web/app/components/app/access-point/built-in-access-points/index.tsx b/web/app/components/app/access-point/built-in-access-points/index.tsx
index 2d9bf69bbfe..7617b83e6ba 100644
--- a/web/app/components/app/access-point/built-in-access-points/index.tsx
+++ b/web/app/components/app/access-point/built-in-access-points/index.tsx
@@ -10,6 +10,7 @@ import { useDocLink } from '@/context/i18n'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { useAppWorkflow } from '@/service/use-workflow'
import { useAccessPointActions } from '../shared/use-access-point-actions'
import { getPublishedWorkflowState, isAdvancedApp } from '../shared/utils'
@@ -46,7 +47,7 @@ export function BuiltInAccessPoints({
isPending: workflowLoading,
} = useAppWorkflow(shouldFetchWorkflow ? appId : '', {
retry: (failureCount, error) => {
- if (error instanceof Response && error.status === 403) return false
+ if (getHttpErrorStatus(error) === 403) return false
return failureCount < 3
},
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
index a8edd2bf7fe..619ad11c3a8 100644
--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
@@ -4,6 +4,7 @@ import CommonLayoutError from '@/app/(commonLayout)/error'
import ErrorBoundary from '@/app/components/base/error-boundary'
import { DETAIL_SIDEBAR_COOKIE_NAME } from '@/app/components/detail-sidebar/cookie'
import { consoleClient, consoleQuery } from '@/service/console'
+import { createHttpError } from '@/service/http-error'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createQueryClientWrapper } from '@/test/console/query-client'
import { renderHook as renderHookWithConsoleState } from '@/test/console/render'
@@ -308,8 +309,8 @@ describe('useConfiguration', () => {
}
})
- it('should retain the legacy unauthorized response for the redirect loading fallback', async () => {
- const response = new Response(null, { status: 401 })
+ it('should retain unauthorized ORPCError for the redirect loading fallback', async () => {
+ const response = createHttpError(new Response(null, { status: 401 }))
mockFetchCollectionList.mockRejectedValueOnce(response)
const queryClient = createTestQueryClient()
seedAccountProfileQuery(queryClient, { id: 'user-1' })
diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
index 83aa1ed7009..1c03656945a 100644
--- a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactElement } from 'react'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
+import { httpErrorFromResponse } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { AppModeEnum } from '@/types/app'
import CreateFromDSLModal from '../index'
@@ -954,7 +955,9 @@ describe('CreateFromDSLModal', () => {
error: 'Invalid YAML format',
})
mockImportDSL.mockRejectedValueOnce(
- Response.json({ message: 'Package checksum mismatch' }, { status: 400 }),
+ await httpErrorFromResponse(
+ Response.json({ message: 'Package checksum mismatch' }, { status: 400 }),
+ ),
)
const { rerender } = render(
@@ -999,7 +1002,7 @@ describe('CreateFromDSLModal', () => {
() => Response.json({ error: 'Import confirmation expired' }, { status: 400 }),
'Import confirmation expired',
],
- ['empty', () => new Response(null, { status: 500 }), undefined],
+ ['empty', () => new Response(null, { status: 500 }), 'HTTP 500'],
] as const)(
'reports a %s HTTP failure when confirming an import',
async (_, response, description) => {
@@ -1010,7 +1013,7 @@ describe('CreateFromDSLModal', () => {
imported_dsl_version: '1.0.0',
current_dsl_version: '2.0.0',
})
- mockImportDSLConfirm.mockRejectedValueOnce(response())
+ mockImportDSLConfirm.mockRejectedValueOnce(await httpErrorFromResponse(response()))
const onClose = vi.fn()
render(
<CreateFromDSLModal
diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsx
index 69a51dfa250..5ba6a84a6ae 100644
--- a/web/app/components/app/create-from-dsl-modal/index.tsx
+++ b/web/app/components/app/create-from-dsl-modal/index.tsx
@@ -33,8 +33,8 @@ import { consoleQuery } from '@/service/console'
import { AppModeEnum as AppMode } from '@/types/app'
import { getRedirection } from '@/utils/app-redirection'
import { trackCreateApp } from '@/utils/create-app-tracking'
+import { getErrorMessage } from '@/utils/error-message'
import { resolveImportedAppRedirectionTarget } from '@/utils/imported-app-redirection'
-import { getAppTransferErrorMessage } from '../transfer-error'
import DSLConfirmModal from './dsl-confirm-modal'
import DSLImportWarningDescription from './dsl-import-warning-description'
import { CreateFromDSLModalTab } from './types'
@@ -241,7 +241,7 @@ function CreateFromDSLModal({
toast.error(
t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
return
@@ -261,7 +261,7 @@ function CreateFromDSLModal({
toast.error(
t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
return
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/content.tsx b/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
index 12b3b85f47d..875fce1a311 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
@@ -7,10 +7,10 @@ import type { DeploymentConfigurationValuesController } from './use-deployment-c
import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
+import { getErrorMessage } from '@/utils/error-message'
import { CredentialsSection } from './credentials-section'
import { DeploymentPrecheckAlert } from './deployment-precheck-alert'
import { EnvironmentVariablesSection } from './environment-variables-section'
-import { getDeploymentErrorMessage } from './utils/deployment-error'
function ConfigurationError({ messages }: { messages: string[] }) {
const { t } = useTranslation(['common'])
@@ -103,7 +103,7 @@ export function DeploymentConfigurationContent({
{!isPrechecking && precheckError && (
<div className={cn('py-4', horizontalPaddingClassName)}>
<ConfigurationError
- messages={[getDeploymentErrorMessage(precheckError) ?? tCommon(($) => $.error)]}
+ messages={[getErrorMessage(precheckError) ?? tCommon(($) => $.error)]}
/>
</div>
)}
@@ -119,7 +119,7 @@ export function DeploymentConfigurationContent({
<div className={cn('py-4', horizontalPaddingClassName)}>
<ConfigurationError
messages={[
- getDeploymentErrorMessage(deploymentOptionsError) ??
+ getErrorMessage(deploymentOptionsError) ??
t(($) => $['deployDrawer.bindingOptionsFailed']),
]}
/>
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts
index 5481e8c24de..92c8f5d7d23 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts
+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-queries.ts
@@ -1,19 +1,7 @@
'use client'
-import type { QueryFunction } from '@tanstack/react-query'
import { skipToken, useQuery } from '@tanstack/react-query'
import { consoleQuery } from '@/service/console'
-import { normalizeDeploymentError } from './utils/deployment-error'
-
-function withNormalizedDeploymentError<TData>(queryFn: QueryFunction<TData>): QueryFunction<TData> {
- return async (context) => {
- try {
- return await queryFn(context)
- } catch (error) {
- throw await normalizeDeploymentError(error)
- }
- }
-}
export function useDeploymentConfigurationQueries({
appId,
@@ -37,10 +25,7 @@ export function useDeploymentConfigurationQueries({
: skipToken,
retry: false,
})
- const precheckQuery = useQuery({
- ...precheckQueryOptions,
- queryFn: withNormalizedDeploymentError(precheckQueryOptions.queryFn),
- })
+ const precheckQuery = useQuery(precheckQueryOptions)
const precheck = precheckQuery.data
const precheckPassed =
precheckQuery.isSuccess && !precheckQuery.isFetching && precheck?.unsupported_nodes.length === 0
@@ -60,10 +45,7 @@ export function useDeploymentConfigurationQueries({
enabled: precheckPassed,
retry: false,
})
- const deploymentOptionsQuery = useQuery({
- ...deploymentOptionsQueryOptions,
- queryFn: withNormalizedDeploymentError(deploymentOptionsQueryOptions.queryFn),
- })
+ const deploymentOptionsQuery = useQuery(deploymentOptionsQueryOptions)
const isPrechecking = Boolean(appId) && (precheckQuery.isLoading || precheckQuery.isFetching)
const isLoadingDeploymentOptions =
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.ts b/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.ts
deleted file mode 100644
index 90554b305a2..00000000000
--- a/web/app/components/app/deploy/shared/deployment-configuration/utils/deployment-error.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-function messageFrom(value: unknown) {
- if (typeof value !== 'object' || value === null) return undefined
-
- if ('message' in value && typeof value.message === 'string')
- return value.message.trim() || undefined
- if ('error' in value && typeof value.error === 'string') return value.error.trim() || undefined
-
- return undefined
-}
-
-export function getDeploymentErrorMessage(error: unknown) {
- if (typeof error === 'object' && error !== null && 'data' in error) {
- const data = error.data
- if (typeof data === 'object' && data !== null && 'body' in data) {
- const bodyMessage = messageFrom(data.body)
- if (bodyMessage) return bodyMessage
- }
-
- const dataMessage = messageFrom(data)
- if (dataMessage) return dataMessage
- }
-
- return messageFrom(error)
-}
-
-export async function normalizeDeploymentError(error: unknown) {
- if (error instanceof Response && !error.bodyUsed) {
- try {
- const response: unknown = await error.clone().json()
- const message = getDeploymentErrorMessage(response)
- if (message) return new Error(message)
- } catch {}
- }
-
- return error
-}
diff --git a/web/app/components/app/transfer-error.ts b/web/app/components/app/transfer-error.ts
deleted file mode 100644
index 86db8945eca..00000000000
--- a/web/app/components/app/transfer-error.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export async function getAppTransferErrorMessage(error: unknown): Promise<string | undefined> {
- if (error instanceof Response) {
- try {
- const body: unknown = await error.clone().json()
- if (body && typeof body === 'object') {
- if ('message' in body && typeof body.message === 'string') return body.message || undefined
- if ('error' in body && typeof body.error === 'string') return body.error || undefined
- }
- } catch {
- return undefined
- }
- }
-
- return error instanceof Error ? error.message || undefined : undefined
-}
diff --git a/web/app/components/app/use-export-app-dsl.ts b/web/app/components/app/use-export-app-dsl.ts
index f12aa32d065..f4cf1ad54b9 100644
--- a/web/app/components/app/use-export-app-dsl.ts
+++ b/web/app/components/app/use-export-app-dsl.ts
@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleClient } from '@/service/console'
import { downloadBlob } from '@/utils/download'
-import { getAppTransferErrorMessage } from './transfer-error'
+import { getErrorMessage } from '@/utils/error-message'
type ExportAppDslInput = {
appId: string
@@ -86,10 +86,7 @@ export async function exportAppDslFile({
}
async function downloadAppDsl(input: ExportAppDslInput, messages: ExportAppDslMessages) {
- const exportPromise = exportAppDslFile(input).catch(async (error: unknown) => {
- throw new Error(await getAppTransferErrorMessage(error), { cause: error })
- })
- await toast.promise(exportPromise, {
+ await toast.promise(exportAppDslFile(input), {
loading: {
title: messages.loading,
},
@@ -99,7 +96,7 @@ async function downloadAppDsl(input: ExportAppDslInput, messages: ExportAppDslMe
}),
error: (error) => ({
title: input.format === 'yaml' ? messages.error : messages.packageError,
- description: error instanceof Error ? error.message || undefined : undefined,
+ description: getErrorMessage(error),
}),
})
@@ -153,7 +150,7 @@ export function useExportWorkflowAppDsl() {
try {
secretEnvList = await getSecretEnvironmentVariables(input.appId)
} catch (error) {
- toast.error(messages.packageError, { description: await getAppTransferErrorMessage(error) })
+ toast.error(messages.packageError, { description: getErrorMessage(error) })
throw error
}
diff --git a/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx b/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx
index 2013d3a51b6..eb677b3a458 100644
--- a/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx
+++ b/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx
@@ -2,6 +2,7 @@ import type { ComponentProps, ReactNode } from 'react'
import type { IChatItem } from '@/app/components/base/chat/chat/type'
import type { AgentLogDetailResponse } from '@/models/log'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import { fetchAgentLogDetail } from '@/service/log'
import AgentLogDetail from '../detail'
@@ -225,12 +226,14 @@ describe('AgentLogDetail', () => {
describe('Edge Cases', () => {
it('should notify on API error', async () => {
- vi.mocked(fetchAgentLogDetail).mockRejectedValue(new Error('API Error'))
+ vi.mocked(fetchAgentLogDetail).mockRejectedValue(
+ createHttpError(new Response(null, { status: 500 }), { message: 'API Error' }),
+ )
renderComponent()
await waitFor(() => {
- expect(mockToast.error).toHaveBeenCalledWith('Error: API Error')
+ expect(mockToast.error).toHaveBeenCalledWith('API Error')
})
})
diff --git a/web/app/components/base/agent-log-modal/detail.tsx b/web/app/components/base/agent-log-modal/detail.tsx
index b79987b690d..2db2606eddb 100644
--- a/web/app/components/base/agent-log-modal/detail.tsx
+++ b/web/app/components/base/agent-log-modal/detail.tsx
@@ -105,7 +105,7 @@ function AgentLogContent({
},
(error) => {
if (!active) return
- toast.error(`${error}`)
+ toast.error(error instanceof Error ? error.message : String(error))
setLoading(false)
},
)
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
index a614c42fbc6..b5a994e6962 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
@@ -5,6 +5,7 @@ import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import { AppToastHost } from '@/app/notifications/host'
+import { httpErrorFromResponse } from '@/service/http-error'
import {
AppSourceType,
delConversation,
@@ -306,9 +307,11 @@ describe('useChatWithHistory', () => {
setConversationIdInfo('environment:environment-code', 'conversation-1')
mockFetchConversations.mockResolvedValue(createConversationData())
mockFetchChatList.mockRejectedValue(
- new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {
- status: 404,
- }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {
+ status: 404,
+ }),
+ ),
)
const { result } = await renderWithClient(() => useChatWithHistory())
diff --git a/web/app/components/base/file-uploader/__tests__/utils.spec.ts b/web/app/components/base/file-uploader/__tests__/utils.spec.ts
index 6b030d1e10f..10d4811498a 100644
--- a/web/app/components/base/file-uploader/__tests__/utils.spec.ts
+++ b/web/app/components/base/file-uploader/__tests__/utils.spec.ts
@@ -2,6 +2,7 @@ import type { TFunction } from 'i18next'
import type { FileEntity } from '../types'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { upload } from '@/service/base'
+import { createHttpError } from '@/service/http-error'
import { withSelectorKey } from '@/test/i18n-mock'
import { TransferMethod } from '@/types/app'
import { FILE_EXTS } from '../../prompt-editor/constants'
@@ -36,19 +37,24 @@ describe('file-uploader utils', () => {
) as unknown as TFunction<['common']>
it('should return forbidden message when error code is forbidden', () => {
- const error = { response: { code: 'forbidden', message: 'Access denied' } }
+ const error = createHttpError(new Response(null, { status: 400 }), {
+ code: 'forbidden',
+ message: 'Access denied',
+ })
expect(getFileUploadErrorMessage(error, 'default', createMockT())).toBe('Access denied')
})
it('should return file_extension_blocked translation when error code matches', () => {
- const error = { response: { code: 'file_extension_blocked' } }
+ const error = createHttpError(new Response(null, { status: 400 }), {
+ code: 'file_extension_blocked',
+ })
expect(getFileUploadErrorMessage(error, 'default', createMockT())).toBe(
'fileUploader.fileExtensionBlocked',
)
})
it('should return default message for other errors', () => {
- const error = { response: { code: 'unknown_error' } }
+ const error = createHttpError(new Response(null, { status: 400 }), { code: 'unknown_error' })
expect(getFileUploadErrorMessage(error, 'Upload failed', createMockT())).toBe('Upload failed')
})
diff --git a/web/app/components/base/file-uploader/utils.ts b/web/app/components/base/file-uploader/utils.ts
index 282530eb0f6..91d53b5f4ae 100644
--- a/web/app/components/base/file-uploader/utils.ts
+++ b/web/app/components/base/file-uploader/utils.ts
@@ -1,6 +1,7 @@
import type { TFunction } from 'i18next'
import type { FileEntity, FilePreviewKind } from './types'
import type { FileResponse } from '@/types/workflow'
+import { ORPCError } from '@orpc/client'
import mime from 'mime'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
@@ -16,13 +17,13 @@ import { FileAppearanceTypeEnum } from './types'
* @returns Localized error message
*/
export const getFileUploadErrorMessage = (
- error: any,
+ error: unknown,
defaultMessage: string,
t: TFunction<['common']>,
): string => {
- const errorCode = error?.response?.code
+ const errorCode = error instanceof ORPCError ? error.code : undefined
- if (errorCode === 'forbidden') return error?.response?.message
+ if (errorCode === 'forbidden') return error instanceof Error ? error.message : defaultMessage
if (errorCode === 'file_extension_blocked')
return t(($) => $['fileUploader.fileExtensionBlocked'], { ns: 'common' })
diff --git a/web/app/components/base/image-uploader/__tests__/utils.spec.ts b/web/app/components/base/image-uploader/__tests__/utils.spec.ts
index 56e7d47d8fc..55e0ebe52d6 100644
--- a/web/app/components/base/image-uploader/__tests__/utils.spec.ts
+++ b/web/app/components/base/image-uploader/__tests__/utils.spec.ts
@@ -1,6 +1,7 @@
import type { TFunction } from 'i18next'
import { waitFor } from '@testing-library/react'
import { upload } from '@/service/base'
+import { createHttpError } from '@/service/http-error'
import { withSelectorKey } from '@/test/i18n-mock'
import { getImageUploadErrorMessage, imageUpload } from '../utils'
@@ -19,7 +20,10 @@ describe('image-uploader utils', () => {
const t = withSelectorKey(translate) as unknown as TFunction<['common']>
const result = getImageUploadErrorMessage(
- { response: { code: 'forbidden', message: 'Forbidden by policy' } },
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'forbidden',
+ message: 'Forbidden by policy',
+ }),
'Default error',
t,
)
@@ -33,7 +37,7 @@ describe('image-uploader utils', () => {
const t = withSelectorKey(translate) as unknown as TFunction<['common']>
const result = getImageUploadErrorMessage(
- { response: { code: 'file_extension_blocked' } },
+ createHttpError(new Response(null, { status: 400 }), { code: 'file_extension_blocked' }),
'Default error',
t,
)
@@ -47,7 +51,7 @@ describe('image-uploader utils', () => {
const t = withSelectorKey(translate) as unknown as TFunction<['common']>
const result = getImageUploadErrorMessage(
- { response: { code: 'unexpected_error' } },
+ createHttpError(new Response(null, { status: 400 }), { code: 'unexpected_error' }),
'Default error',
t,
)
diff --git a/web/app/components/base/image-uploader/utils.ts b/web/app/components/base/image-uploader/utils.ts
index 8e7a36c718a..55b6770278d 100644
--- a/web/app/components/base/image-uploader/utils.ts
+++ b/web/app/components/base/image-uploader/utils.ts
@@ -1,4 +1,5 @@
import type { TFunction } from 'i18next'
+import { ORPCError } from '@orpc/client'
import { upload } from '@/service/base'
/**
@@ -9,13 +10,13 @@ import { upload } from '@/service/base'
* @returns Localized error message
*/
export const getImageUploadErrorMessage = (
- error: any,
+ error: unknown,
defaultMessage: string,
t: TFunction<['common']>,
): string => {
- const errorCode = error?.response?.code
+ const errorCode = error instanceof ORPCError ? error.code : undefined
- if (errorCode === 'forbidden') return error?.response?.message
+ if (errorCode === 'forbidden') return error instanceof Error ? error.message : defaultMessage
if (errorCode === 'file_extension_blocked')
return t(($) => $['fileUploader.fileExtensionBlocked'], { ns: 'common' })
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
index d8c52eb6dbc..7c56bb112fc 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { httpErrorFromResponse } from '@/service/http-error'
import { CreateFromDSLModalTab, useDSLImport } from '../use-dsl-import'
const mockPush = vi.fn()
@@ -469,14 +470,16 @@ describe('useDSLImport', () => {
it('should show response error when import request rejects with a response body', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
mockImportDSL.mockRejectedValue(
- new Response(
- JSON.stringify({
- error: 'Missing rag_pipeline data in YAML content',
- }),
- {
- status: 400,
- headers: { 'Content-Type': 'application/json' },
- },
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ error: 'Missing rag_pipeline data in YAML content',
+ }),
+ {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
),
)
@@ -820,14 +823,16 @@ describe('useDSLImport', () => {
)
mockImportDSLConfirm.mockRejectedValue(
- new Response(
- JSON.stringify({
- error: 'Import information expired or does not exist',
- }),
- {
- status: 400,
- headers: { 'Content-Type': 'application/json' },
- },
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ error: 'Import information expired or does not exist',
+ }),
+ {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
),
)
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
index 4b27aad5970..7afbf308630 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
@@ -7,6 +7,7 @@ import { toast } from '@/app/notifications'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
import { useRouter } from '@/next/navigation'
import { useImportPipelineDSL, useImportPipelineDSLConfirm } from '@/service/use-pipeline'
+import { getErrorMessage } from '@/utils/error-message'
export const CreateFromDSLModalTab = {
FROM_FILE: 'from-file',
@@ -25,28 +26,6 @@ type DSLVersions = {
importedVersion: string
systemVersion: string
}
-type ImportErrorResponse = {
- message?: unknown
- error?: unknown
-}
-const getNonEmptyString = (value: unknown): string | undefined => {
- if (typeof value !== 'string') return undefined
-
- const trimmedValue = value.trim()
- return trimmedValue || undefined
-}
-const getImportErrorMessage = async (error: unknown): Promise<string | undefined> => {
- if (error instanceof Response && !error.bodyUsed) {
- try {
- const errorData = (await error.clone().json()) as ImportErrorResponse
- return getNonEmptyString(errorData.message) ?? getNonEmptyString(errorData.error)
- } catch {}
- }
-
- if (error instanceof Error) return getNonEmptyString(error.message)
-
- return undefined
-}
export const useDSLImport = ({
activeTab = CreateFromDSLModalTab.FROM_FILE,
dslUrl = '',
@@ -149,7 +128,7 @@ export const useDSLImport = ({
notifyError(response.error)
}
} catch (error) {
- notifyError(await getImportErrorMessage(error))
+ notifyError(getErrorMessage(error)?.trim() || undefined)
} finally {
isCreatingRef.current = false
}
@@ -186,7 +165,7 @@ export const useDSLImport = ({
notifyError(error)
}
} catch (error) {
- notifyError(await getImportErrorMessage(error))
+ notifyError(getErrorMessage(error)?.trim() || undefined)
} finally {
setIsConfirming(false)
}
diff --git a/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx b/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx
index 260e546842a..c7add52e3d6 100644
--- a/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
// Component Import (after mocks)
import FireCrawl from '../index'
@@ -586,9 +587,9 @@ describe('FireCrawl', () => {
it('should handle API exception during status check', async () => {
const user = userEvent.setup()
mockCreateFirecrawlTask.mockResolvedValueOnce({ job_id: 'test-job' })
- mockCheckFirecrawlTaskStatus.mockRejectedValueOnce({
- json: () => Promise.resolve({ message: 'Status check failed' }),
- })
+ mockCheckFirecrawlTaskStatus.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 502 }), { message: 'Status check failed' }),
+ )
render(<FireCrawl {...defaultProps} />)
@@ -601,6 +602,7 @@ describe('FireCrawl', () => {
await waitFor(() => {
expect(screen.getByText(/exceptionErrorTitle/i))!.toBeInTheDocument()
})
+ expect(screen.getByText('Status check failed')).toBeInTheDocument()
})
it('should display error message from API', async () => {
diff --git a/web/app/components/datasets/create/website/firecrawl/index.tsx b/web/app/components/datasets/create/website/firecrawl/index.tsx
index 9635d59fc03..d5b9f3f8e1b 100644
--- a/web/app/components/datasets/create/website/firecrawl/index.tsx
+++ b/web/app/components/datasets/create/website/firecrawl/index.tsx
@@ -157,10 +157,9 @@ const FireCrawl: FC<Props> = ({
return await waitForCrawlFinished(jobId)
} catch (e: any) {
if (!isMountedRef.current) return cancelledResult
- const errorBody = typeof e?.json === 'function' ? await e.json() : undefined
return {
isError: true,
- errorMessage: errorBody?.message,
+ errorMessage: e instanceof Error ? e.message : undefined,
data: {
data: [],
},
diff --git a/web/app/components/datasets/create/website/jina-reader/__tests__/index.spec.tsx b/web/app/components/datasets/create/website/jina-reader/__tests__/index.spec.tsx
index 8c306b77dd4..1c2ca7cd76e 100644
--- a/web/app/components/datasets/create/website/jina-reader/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create/website/jina-reader/__tests__/index.spec.tsx
@@ -3,6 +3,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { checkJinaReaderTaskStatus, createJinaReaderTask } from '@/service/datasets'
+import { createHttpError } from '@/service/http-error'
import { sleep } from '@/utils'
import JinaReader from '../index'
@@ -692,9 +693,9 @@ describe('JinaReader', () => {
const mockCheckStatus = checkJinaReaderTaskStatus as Mock
mockCreateTask.mockResolvedValueOnce({ job_id: 'error-job' })
- mockCheckStatus.mockRejectedValueOnce({
- json: () => Promise.resolve({ message: 'API Error occurred' }),
- })
+ mockCheckStatus.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 502 }), { message: 'API Error occurred' }),
+ )
const props = createDefaultProps()
@@ -708,6 +709,7 @@ describe('JinaReader', () => {
screen.getByText('datasetCreation.stepOne.website.exceptionErrorTitle'),
)!.toBeInTheDocument()
})
+ expect(screen.getByText('API Error occurred')).toBeInTheDocument()
})
it('should limit total to crawlOptions.limit', async () => {
diff --git a/web/app/components/datasets/create/website/jina-reader/index.tsx b/web/app/components/datasets/create/website/jina-reader/index.tsx
index f30bed59c47..3c3930f30b2 100644
--- a/web/app/components/datasets/create/website/jina-reader/index.tsx
+++ b/web/app/components/datasets/create/website/jina-reader/index.tsx
@@ -125,10 +125,9 @@ const JinaReader: FC<Props> = ({
await sleep(2500)
return await waitForCrawlFinished(jobId)
} catch (e: any) {
- const errorBody = await e.json()
return {
isError: true,
- errorMessage: errorBody.message,
+ errorMessage: e instanceof Error ? e.message : undefined,
data: {
data: [],
},
diff --git a/web/app/components/datasets/create/website/watercrawl/__tests__/index.spec.tsx b/web/app/components/datasets/create/website/watercrawl/__tests__/index.spec.tsx
index 8f64a270e19..ebf2613dea2 100644
--- a/web/app/components/datasets/create/website/watercrawl/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create/website/watercrawl/__tests__/index.spec.tsx
@@ -3,6 +3,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { checkWatercrawlTaskStatus, createWatercrawlTask } from '@/service/datasets'
+import { createHttpError } from '@/service/http-error'
import { sleep } from '@/utils'
import WaterCrawl from '../index'
@@ -699,9 +700,9 @@ describe('WaterCrawl', () => {
const mockCheckStatus = checkWatercrawlTaskStatus as Mock
mockCreateTask.mockResolvedValueOnce({ job_id: 'error-job' })
- mockCheckStatus.mockRejectedValueOnce({
- json: () => Promise.resolve({ message: 'API Error occurred' }),
- })
+ mockCheckStatus.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 502 }), { message: 'API Error occurred' }),
+ )
const props = createDefaultProps()
@@ -715,6 +716,7 @@ describe('WaterCrawl', () => {
screen.getByText('datasetCreation.stepOne.website.exceptionErrorTitle'),
)!.toBeInTheDocument()
})
+ expect(screen.getByText('API Error occurred')).toBeInTheDocument()
})
it('should limit total to crawlOptions.limit', async () => {
diff --git a/web/app/components/datasets/create/website/watercrawl/index.tsx b/web/app/components/datasets/create/website/watercrawl/index.tsx
index 97ce25cede2..593475bfba3 100644
--- a/web/app/components/datasets/create/website/watercrawl/index.tsx
+++ b/web/app/components/datasets/create/website/watercrawl/index.tsx
@@ -131,21 +131,7 @@ const WaterCrawl: FC<Props> = ({
await sleep(2500)
return await waitForCrawlFinished(jobId)
} catch (error: unknown) {
- let errorMessage = ''
- const maybeErrorWithJson = error as {
- json?: () => Promise<unknown>
- message?: unknown
- } | null
- if (maybeErrorWithJson?.json) {
- try {
- const errorBody = (await maybeErrorWithJson.json()) as {
- message?: unknown
- } | null
- if (typeof errorBody?.message === 'string') errorMessage = errorBody.message
- } catch {}
- }
- if (!errorMessage && typeof maybeErrorWithJson?.message === 'string')
- errorMessage = maybeErrorWithJson.message
+ const errorMessage = error instanceof Error ? error.message : ''
return {
isError: true,
errorMessage,
diff --git a/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx b/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx
index edc3b24c259..105857911a4 100644
--- a/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx
+++ b/web/app/components/datasets/documents/components/__tests__/rename-modal.spec.tsx
@@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
// Import after mock
import { renameDocumentName } from '@/service/datasets'
+import { createHttpError } from '@/service/http-error'
import RenameModal from '../rename-modal'
const { mockToastSuccess, mockToastError } = vi.hoisted(() => ({
@@ -159,7 +160,7 @@ describe('RenameModal', () => {
describe('Error Handling', () => {
it('should handle API error gracefully', async () => {
- const error = new Error('API Error')
+ const error = createHttpError(new Response(null, { status: 500 }), { message: 'API Error' })
mockRenameDocumentName.mockRejectedValueOnce(error)
const handleSaved = vi.fn()
const handleClose = vi.fn()
@@ -173,7 +174,7 @@ describe('RenameModal', () => {
// onSaved and onClose should not be called on error
expect(handleSaved).not.toHaveBeenCalled()
expect(handleClose).not.toHaveBeenCalled()
- expect(mockToastError).toHaveBeenCalledWith('Error: API Error')
+ expect(mockToastError).toHaveBeenCalledWith('API Error')
})
})
})
diff --git a/web/app/components/datasets/documents/components/rename-modal.tsx b/web/app/components/datasets/documents/components/rename-modal.tsx
index 9411f6e60a0..4de779522d9 100644
--- a/web/app/components/datasets/documents/components/rename-modal.tsx
+++ b/web/app/components/datasets/documents/components/rename-modal.tsx
@@ -40,7 +40,7 @@ const RenameModal: FC<Props> = ({ documentId, datasetId, name, onClose, onSaved
onSaved()
onClose()
} catch (error) {
- if (error) toast.error(error.toString())
+ if (error) toast.error(error instanceof Error ? error.message : String(error))
} finally {
setSaveLoadingFalse()
}
diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts
index d3d6d95e9df..979891f50fd 100644
--- a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts
+++ b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-state.ts
@@ -110,12 +110,9 @@ export const useDatasetCardState = ({ dataset, onSuccess }: UseDatasetCardStateO
showConfirmDelete: true,
}))
} catch (e: unknown) {
- if (e instanceof Response) {
- const res = await e.json()
- toast.error(res?.message || t(($) => $.unknownError, { ns: 'dataset' }))
- } else {
- toast.error((e as Error)?.message || t(($) => $.unknownError, { ns: 'dataset' }))
- }
+ toast.error(
+ (e instanceof Error ? e.message : '') || t(($) => $.unknownError, { ns: 'dataset' }),
+ )
}
}, [dataset.id, queryClient, t])
diff --git a/web/app/components/explore/installed-app/__tests__/index.spec.tsx b/web/app/components/explore/installed-app/__tests__/index.spec.tsx
index 1eb5b2fc023..0e8a46e27f9 100644
--- a/web/app/components/explore/installed-app/__tests__/index.spec.tsx
+++ b/web/app/components/explore/installed-app/__tests__/index.spec.tsx
@@ -7,6 +7,7 @@ import { screen, waitFor } from '@testing-library/react'
import { useWebAppStore } from '@/context/web-app-context'
import { AccessMode } from '@/models/access-control'
import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'
+import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import InstalledApp from '../index'
@@ -253,7 +254,7 @@ describe('InstalledApp', () => {
})
it('distinguishes a missing installed app from a recoverable detail failure', async () => {
- mocks.getInstalledApp.mockRejectedValue(new Response(null, { status: 404 }))
+ mocks.getInstalledApp.mockRejectedValue(createHttpError(new Response(null, { status: 404 })))
const { unmount } = renderWithConsoleQuery(<InstalledApp id="missing-app" />)
expect(await screen.findByText(/404/)).toBeInTheDocument()
unmount()
diff --git a/web/app/components/explore/installed-app/index.tsx b/web/app/components/explore/installed-app/index.tsx
index 6aa0786756a..6fe803a15a4 100644
--- a/web/app/components/explore/installed-app/index.tsx
+++ b/web/app/components/explore/installed-app/index.tsx
@@ -1,4 +1,5 @@
'use client'
+
import type { AppMode } from '@dify/contracts/api/console/installed-apps/types.gen'
import type { AppData } from '@/models/share'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
@@ -12,6 +13,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { AccessMode } from '@/models/access-control'
import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'
import { consoleQuery } from '@/service/console'
+import { isNotFoundError } from '@/service/http-error'
import AppUnavailable from '../../base/app-unavailable'
import { toInstalledAppAccessMode, toInstalledAppMeta, toInstalledAppParameters } from './runtime'
@@ -192,7 +194,7 @@ const InstalledApp = ({ id }: { id: string }) => {
)
}
if (installedAppError) {
- const isNotFound = installedAppError instanceof Response && installedAppError.status === 404
+ const isNotFound = isNotFoundError(installedAppError)
return (
<InstalledAppFrame>
<div className="flex h-full items-center justify-center">
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx
index 16a5c0eab78..08194115a1f 100644
--- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.spec.tsx
@@ -5,6 +5,7 @@ import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi } from 'vite-plus/test'
import { useWorkspaceRoleList } from '@/service/access-control/use-workspace-roles'
+import { createHttpError } from '@/service/http-error'
import { seedCurrentWorkspaceQuery } from '@/test/console/current-workspace'
import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'
import { QueryClientTestProvider } from '@/test/console/query-provider'
@@ -546,10 +547,9 @@ describe('InviteModal', () => {
['invalid_role', /members\.invalidRole/i, 'role', 'combobox'],
])('maps %s server validation to the owning field', async (code, message, fieldName, role) => {
const user = userEvent.setup()
- inviteMember.mockRejectedValue({
- code: 'BAD_REQUEST',
- data: { body: { code, message: 'Backend message' } },
- })
+ inviteMember.mockRejectedValue(
+ createHttpError(new Response(null, { status: 400 }), { code, message: 'Backend message' }),
+ )
await renderModal()
await addRecipients(user, '[email protected], [email protected]')
@@ -568,10 +568,12 @@ describe('InviteModal', () => {
it('keeps a role server error visible when the user only opens the selector', async () => {
const user = userEvent.setup()
- inviteMember.mockRejectedValue({
- code: 'BAD_REQUEST',
- data: { body: { code: 'invalid_role', message: 'Backend message' } },
- })
+ inviteMember.mockRejectedValue(
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'invalid_role',
+ message: 'Backend message',
+ }),
+ )
await renderModal()
await addRecipients(user, '[email protected]')
@@ -605,10 +607,12 @@ describe('InviteModal', () => {
await waitFor(() => expect(input).toBeDisabled())
await act(async () =>
- rejectInvite({
- code: 'BAD_REQUEST',
- data: { body: { code: 'limit_exceeded', message: 'Backend message' } },
- }),
+ rejectInvite(
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'limit_exceeded',
+ message: 'Backend message',
+ }),
+ ),
)
expect(await screen.findByText(/members\.inviteLimitExceeded/i)).toBeInTheDocument()
@@ -619,10 +623,12 @@ describe('InviteModal', () => {
it('should clear an email server error when the user edits and successfully retries', async () => {
const user = userEvent.setup()
inviteMember
- .mockRejectedValueOnce({
- code: 'BAD_REQUEST',
- data: { body: { code: 'limit_exceeded', message: 'Backend message' } },
- })
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'limit_exceeded',
+ message: 'Backend message',
+ }),
+ )
.mockResolvedValueOnce({
result: 'success',
invitation_results: [],
@@ -657,10 +663,12 @@ describe('InviteModal', () => {
it('should clear an email server error when a recipient is removed before retrying', async () => {
const user = userEvent.setup()
inviteMember
- .mockRejectedValueOnce({
- code: 'BAD_REQUEST',
- data: { body: { code: 'limit_exceeded', message: 'Backend message' } },
- })
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), {
+ code: 'limit_exceeded',
+ message: 'Backend message',
+ }),
+ )
.mockResolvedValueOnce({
result: 'success',
invitation_results: [],
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/invite-error.spec.ts b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/invite-error.spec.ts
index 863e9987395..9f206520291 100644
--- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/invite-error.spec.ts
+++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/invite-error.spec.ts
@@ -1,15 +1,23 @@
+import { createHttpError } from '@/service/http-error'
import { getInviteErrorCode } from '../invite-error'
describe('getInviteErrorCode', () => {
it.each(['invalid_param', 'invalid_role', 'limit_exceeded'])(
- 'reads the documented %s code from the contract error body',
+ 'reads the documented %s code from the HTTP error',
(code) => {
- expect(getInviteErrorCode({ data: { body: { code } } })).toBe(code)
+ expect(
+ getInviteErrorCode(createHttpError(new Response(null, { status: 400 }), { code })),
+ ).toBe(code)
},
)
it('ignores transport and undocumented error codes', () => {
- expect(getInviteErrorCode({ code: 'BAD_REQUEST' })).toBeNull()
- expect(getInviteErrorCode({ data: { body: { code: 'invalid-role' } } })).toBeNull()
+ expect(getInviteErrorCode(new TypeError('Failed to fetch'))).toBeNull()
+ expect(getInviteErrorCode(createHttpError(new Response(null, { status: 503 })))).toBeNull()
+ expect(
+ getInviteErrorCode(
+ createHttpError(new Response(null, { status: 400 }), { code: 'invalid-role' }),
+ ),
+ ).toBeNull()
})
})
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/invite-error.ts b/web/app/components/header/account-setting/members-page/invite-modal/invite-error.ts
index 0a24ee0a8ef..2339e24f3a7 100644
--- a/web/app/components/header/account-setting/members-page/invite-modal/invite-error.ts
+++ b/web/app/components/header/account-setting/members-page/invite-modal/invite-error.ts
@@ -1,4 +1,5 @@
import type { MemberInviteErrorResponse } from '@dify/contracts/api/console/workspaces/types.gen'
+import { ORPCError } from '@orpc/client'
type InviteErrorCode = MemberInviteErrorResponse['code']
@@ -8,17 +9,9 @@ const INVITE_ERROR_CODES = new Set<InviteErrorCode>([
'limit_exceeded',
])
-function getRecord(value: unknown) {
- return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
-}
-
export function getInviteErrorCode(error: unknown): InviteErrorCode | null {
- const errorRecord = getRecord(error)
- const dataRecord = getRecord(errorRecord?.data)
- const bodyRecord = getRecord(dataRecord?.body)
- const code = bodyRecord?.code ?? errorRecord?.code
+ if (!(error instanceof ORPCError)) return null
+ const code = error.code
- return typeof code === 'string' && INVITE_ERROR_CODES.has(code as InviteErrorCode)
- ? (code as InviteErrorCode)
- : null
+ return INVITE_ERROR_CODES.has(code as InviteErrorCode) ? (code as InviteErrorCode) : null
}
diff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx
index 859b4e923ad..e9437fbbfad 100644
--- a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx
+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx
@@ -10,6 +10,7 @@ import { toast } from '@/app/notifications'
import { currentWorkspaceAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { ownershipTransfer, sendOwnerEmail, verifyOwnerEmail } from '@/service/common'
+import { getErrorMessage } from '@/utils/error-message'
import MemberSelector from './member-selector'
type Props = Readonly<{
@@ -23,10 +24,6 @@ const STEP = {
}
type Step = (typeof STEP)[keyof typeof STEP]
-const getErrorMessage = (error: unknown) => {
- return error instanceof Error ? error.message : ''
-}
-
const TransferOwnershipModal = ({ onClose, show }: Props) => {
const { t } = useTranslation(['common', 'workspaceMembers'])
const verificationCodeInputId = React.useId()
@@ -82,7 +79,7 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {
toast.error('Verifying email failed')
}
} catch (error) {
- toast.error(`Error verifying email: ${getErrorMessage(error)}`)
+ toast.error(`Error verifying email: ${getErrorMessage(error) ?? ''}`)
}
}
const sendCodeToOriginEmail = async () => {
@@ -105,7 +102,7 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {
})
globalThis.location.reload()
} catch (error) {
- toast.error(`Error ownership transfer: ${getErrorMessage(error)}`)
+ toast.error(`Error ownership transfer: ${getErrorMessage(error) ?? ''}`)
} finally {
setIsTransfer(false)
}
diff --git a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
index 79c628a0b60..d4243ebf6ac 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
@@ -6,6 +6,7 @@ import type {
} from '../../../types'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { PluginCategoryEnum } from '../../../types'
import {
convertRepoToUrl,
@@ -1122,9 +1123,9 @@ describe('InstallFromGitHub', () => {
// ================================
describe('Error Handling', () => {
it('should handle API error with response message', async () => {
- mockGetIconUrl.mockRejectedValue({
- response: { message: 'API Error Message' },
- })
+ mockGetIconUrl.mockRejectedValue(
+ createHttpError(new Response(null, { status: 500 }), { message: 'API Error Message' }),
+ )
render(<InstallFromGitHub {...defaultProps} updatePayload={createUpdatePayload()} />)
@@ -1147,9 +1148,7 @@ describe('InstallFromGitHub', () => {
await waitFor(() => {
expect(screen.getByTestId('installed-step')).toBeInTheDocument()
expect(screen.getByTestId('is-failed')).toHaveTextContent('true')
- expect(screen.getByTestId('error-msg')).toHaveTextContent(
- 'plugin.installModal.installFailedDesc',
- )
+ expect(screen.getByTestId('error-msg')).toHaveTextContent('Generic error')
})
})
})
diff --git a/web/app/components/plugins/install-plugin/install-from-github/index.tsx b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
index b11f0133300..ff711629552 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
@@ -112,7 +112,8 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
const handleError = (e: any, isInstall: boolean) => {
const message =
- e?.response?.message || t(($) => $['installModal.installFailedDesc'], { ns: 'plugin' })
+ (e instanceof Error ? e.message : undefined) ||
+ t(($) => $['installModal.installFailedDesc'], { ns: 'plugin' })
setErrorMsg(message)
setState((prevState) => ({
...prevState,
diff --git a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
index f4e3bdda887..a6ad4833380 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
@@ -2,6 +2,7 @@ import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../../typ
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { PluginCategoryEnum } from '../../../../types'
import SelectPackage from '../selectPackage'
@@ -321,7 +322,9 @@ describe('SelectPackage', () => {
})
it('should call onFailed with response message on upload error', async () => {
- mockHandleUpload.mockRejectedValue({ response: { message: 'API Error' } })
+ mockHandleUpload.mockRejectedValue(
+ createHttpError(new Response(null, { status: 500 }), { message: 'API Error' }),
+ )
const onFailed = vi.fn()
renderSelectPackage({
@@ -350,7 +353,7 @@ describe('SelectPackage', () => {
fireEvent.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
await waitFor(() => {
- expect(onFailed).toHaveBeenCalledWith('plugin.installFromGitHub.uploadFailed')
+ expect(onFailed).toHaveBeenCalledWith('Network error')
})
})
@@ -684,7 +687,9 @@ describe('SelectPackage', () => {
// ================================
describe('Error Response Handling', () => {
it('should handle error with response.message property', async () => {
- mockHandleUpload.mockRejectedValue({ response: { message: 'Custom API Error' } })
+ mockHandleUpload.mockRejectedValue(
+ createHttpError(new Response(null, { status: 500 }), { message: 'Custom API Error' }),
+ )
const onFailed = vi.fn()
renderSelectPackage({
@@ -701,7 +706,7 @@ describe('SelectPackage', () => {
})
it('should handle error with empty response object', async () => {
- mockHandleUpload.mockRejectedValue({ response: {} })
+ mockHandleUpload.mockRejectedValue(createHttpError(new Response(null, { status: 500 }), {}))
const onFailed = vi.fn()
renderSelectPackage({
@@ -713,7 +718,7 @@ describe('SelectPackage', () => {
fireEvent.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
await waitFor(() => {
- expect(onFailed).toHaveBeenCalledWith('plugin.installFromGitHub.uploadFailed')
+ expect(onFailed).toHaveBeenCalledWith('HTTP 500')
})
})
@@ -735,7 +740,9 @@ describe('SelectPackage', () => {
})
it('should handle error with response but no message', async () => {
- mockHandleUpload.mockRejectedValue({ response: { status: 500 } })
+ mockHandleUpload.mockRejectedValue(
+ createHttpError(new Response(null, { status: 500 }), { status: 500 }),
+ )
const onFailed = vi.fn()
renderSelectPackage({
@@ -747,7 +754,7 @@ describe('SelectPackage', () => {
fireEvent.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
await waitFor(() => {
- expect(onFailed).toHaveBeenCalledWith('plugin.installFromGitHub.uploadFailed')
+ expect(onFailed).toHaveBeenCalledWith('HTTP 500')
})
})
diff --git a/web/app/components/plugins/install-plugin/install-from-github/steps/selectPackage.tsx b/web/app/components/plugins/install-plugin/install-from-github/steps/selectPackage.tsx
index 2abc2e475c3..8a83084308c 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/steps/selectPackage.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/steps/selectPackage.tsx
@@ -69,7 +69,7 @@ const SelectPackage: React.FC<SelectPackageProps> = ({
})
})
} catch (e: any) {
- if (e.response?.message) onFailed(e.response?.message)
+ if (e instanceof Error && e.message) onFailed(e.message)
else onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
} finally {
setIsUploading(false)
diff --git a/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx b/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
index 658460c29c2..263703d02f6 100644
--- a/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
@@ -2,6 +2,7 @@ import type { Dependency, PluginDeclaration } from '../../../../types'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { PluginCategoryEnum } from '../../../../types'
import Uploading from '../uploading'
@@ -153,9 +154,9 @@ describe('Uploading', () => {
it('should call onFailed when upload fails with error message', async () => {
const errorMessage = 'Upload failed: file too large'
- mockUploadFile.mockRejectedValue({
- response: { message: errorMessage },
- })
+ mockUploadFile.mockRejectedValue(
+ createHttpError(new Response(null, { status: 413 }), { message: errorMessage }),
+ )
const onFailed = vi.fn()
render(<Uploading {...defaultProps} onFailed={onFailed} />)
@@ -165,27 +166,14 @@ describe('Uploading', () => {
})
})
- // NOTE: Some upload endpoints have historically returned successful plugin upload
- // payloads through rejected XHR objects, so the component accepts both resolved
- // responses and rejected responses without an error message.
-
- it('should call onPackageUploaded when upload rejects without error message (success case)', async () => {
- const mockResult = {
- unique_identifier: 'test-uid',
- manifest: createMockManifest(),
- }
- mockUploadFile.mockRejectedValue({
- response: mockResult,
- })
+ it('should use the localized failure when the upload never reaches the server', async () => {
+ mockUploadFile.mockRejectedValue(new TypeError('Failed to fetch'))
- const onPackageUploaded = vi.fn()
- render(<Uploading {...defaultProps} isBundle={false} onPackageUploaded={onPackageUploaded} />)
+ const onFailed = vi.fn()
+ render(<Uploading {...defaultProps} onFailed={onFailed} />)
await waitFor(() => {
- expect(onPackageUploaded).toHaveBeenCalledWith({
- uniqueIdentifier: mockResult.unique_identifier,
- manifest: mockResult.manifest,
- })
+ expect(onFailed).toHaveBeenCalledWith('plugin.installModal.uploadFailed')
})
})
@@ -207,20 +195,6 @@ describe('Uploading', () => {
})
})
- it('should call onBundleUploaded when upload rejects without error message (success case)', async () => {
- const mockDependencies = createMockDependencies()
- mockUploadFile.mockRejectedValue({
- response: mockDependencies,
- })
-
- const onBundleUploaded = vi.fn()
- render(<Uploading {...defaultProps} isBundle onBundleUploaded={onBundleUploaded} />)
-
- await waitFor(() => {
- expect(onBundleUploaded).toHaveBeenCalledWith(mockDependencies)
- })
- })
-
it('should call onBundleUploaded when upload resolves with bundle response', async () => {
const mockDependencies = createMockDependencies()
mockUploadFile.mockResolvedValue(mockDependencies)
@@ -283,9 +257,7 @@ describe('Uploading', () => {
// ================================
describe('Edge Cases', () => {
it('should fail gracefully when upload response is empty', async () => {
- mockUploadFile.mockRejectedValue({
- response: {},
- })
+ mockUploadFile.mockResolvedValue({})
const onPackageUploaded = vi.fn()
const onFailed = vi.fn()
@@ -300,9 +272,7 @@ describe('Uploading', () => {
})
it('should fail gracefully when upload response has no manifest', async () => {
- mockUploadFile.mockRejectedValue({
- response: { unique_identifier: 'only-uid' },
- })
+ mockUploadFile.mockResolvedValue({ unique_identifier: 'only-uid' })
const onPackageUploaded = vi.fn()
const onFailed = vi.fn()
@@ -317,9 +287,7 @@ describe('Uploading', () => {
})
it('should fail gracefully when upload response is null', async () => {
- mockUploadFile.mockRejectedValue({
- response: null,
- })
+ mockUploadFile.mockResolvedValue(null)
const onPackageUploaded = vi.fn()
const onFailed = vi.fn()
diff --git a/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx b/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
index fca205a5e2c..4f53561bfba 100644
--- a/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
@@ -2,6 +2,7 @@
import type { FC } from 'react'
import type { Dependency, Plugin, PluginDeclaration } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
+import { ORPCError } from '@orpc/client'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { uploadFile } from '@/service/plugins'
@@ -14,10 +15,6 @@ type PackageUploadResponse = {
manifest: PluginDeclaration
}
-type UploadFailureResponse = {
- message?: string
-}
-
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
@@ -28,18 +25,6 @@ function isPackageUploadResponse(value: unknown): value is PackageUploadResponse
return typeof value.unique_identifier === 'string' && isObject(value.manifest)
}
-function getRejectedResponse(error: unknown): unknown {
- if (!isObject(error) || !('response' in error)) return undefined
-
- return error.response
-}
-
-function getUploadFailureMessage(response: unknown): string | undefined {
- if (!isObject(response)) return undefined
-
- return (response as UploadFailureResponse).message
-}
-
type Props = Readonly<{
isBundle: boolean
file: File
@@ -87,15 +72,15 @@ const Uploading: FC<Props> = ({
try {
handleUploadedResponse(await uploadFile(file, isBundle))
} catch (error: unknown) {
- const response = getRejectedResponse(error)
- const message = getUploadFailureMessage(response)
+ // Only server answers carry a user-facing message; transport errors use the localized fallback.
+ const message = error instanceof ORPCError ? error.message : undefined
if (message) {
onFailed(message)
return
}
- handleUploadedResponse(response)
+ onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
}
- }, [file, handleUploadedResponse, isBundle, onFailed])
+ }, [file, handleUploadedResponse, isBundle, onFailed, t])
React.useEffect(() => {
handleUpload()
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
index b6ee7d8e686..3a8e737be02 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
@@ -128,7 +128,7 @@ vi.mock('@/service/use-triggers', () => ({
}),
}))
-const mockParsePluginErrorMessage = vi.fn().mockResolvedValue(null)
+const mockParsePluginErrorMessage = vi.fn().mockReturnValue(null)
vi.mock('@/utils/error-parser', () => ({
parsePluginErrorMessage: (...args: unknown[]) => mockParsePluginErrorMessage(...args),
}))
@@ -294,7 +294,7 @@ describe('CommonCreateModal', () => {
})
setMockGetFormReturnsNull(false)
setMockFormValidation(true, true, true) // All forms validated by default
- mockParsePluginErrorMessage.mockResolvedValue(null)
+ mockParsePluginErrorMessage.mockReturnValue(null)
})
afterEach(() => {
@@ -1222,7 +1222,7 @@ describe('CommonCreateModal', () => {
describe('Error Message Parsing', () => {
it('should use parsed error message when available for verify error', async () => {
- mockParsePluginErrorMessage.mockResolvedValue('Custom parsed error')
+ mockParsePluginErrorMessage.mockReturnValue('Custom parsed error')
const detailWithCredentials = createMockPluginDetail({
declaration: {
@@ -1262,7 +1262,7 @@ describe('CommonCreateModal', () => {
})
it('should use parsed error message when available for build error', async () => {
- mockParsePluginErrorMessage.mockResolvedValue('Custom build error')
+ mockParsePluginErrorMessage.mockReturnValue('Custom build error')
const builder = createMockSubscriptionBuilder()
mockBuildSubscription.mockImplementation((params, { onError }) => {
@@ -1292,7 +1292,7 @@ describe('CommonCreateModal', () => {
})
it('should use fallback error message when parsePluginErrorMessage returns null', async () => {
- mockParsePluginErrorMessage.mockResolvedValue(null)
+ mockParsePluginErrorMessage.mockReturnValue(null)
const builder = createMockSubscriptionBuilder()
mockBuildSubscription.mockImplementation((params, { onError }) => {
@@ -1318,7 +1318,7 @@ describe('CommonCreateModal', () => {
})
it('should use parsed error message for update builder error', async () => {
- mockParsePluginErrorMessage.mockResolvedValue('Custom update error')
+ mockParsePluginErrorMessage.mockReturnValue('Custom update error')
const detailWithManualSchema = createMockPluginDetail({
declaration: {
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
index 6b8cb55b9e1..c60948c5db1 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
@@ -7,6 +7,7 @@ import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
+import { createHttpError } from '@/service/http-error'
import { OAuthClientSettingsModal } from '../oauth-client'
type PluginDetail = {
@@ -680,7 +681,7 @@ describe('OAuthClientSettingsModal', () => {
})
})
- it('should extract error message from object with message property', () => {
+ it('should extract the backend message from an API error', () => {
const configWithCustomEnabled = createMockOAuthConfig({
system_configured: false,
custom_enabled: true,
@@ -688,7 +689,9 @@ describe('OAuthClientSettingsModal', () => {
})
mockDeleteOAuth.mockImplementation((provider, { onError }) => {
- onError({ message: 'Object error message' })
+ onError(
+ createHttpError(new Response(null, { status: 503 }), { message: 'Object error message' }),
+ )
})
render(<OAuthClientSettingsModal {...defaultProps} oauthConfig={configWithCustomEnabled} />)
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.spec.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.spec.ts
index 74443ea3312..4ca4b14435f 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.spec.ts
@@ -100,7 +100,7 @@ vi.mock('@/app/notifications', () => ({
},
}))
-const mockParsePluginErrorMessage = vi.fn().mockResolvedValue(null)
+const mockParsePluginErrorMessage = vi.fn().mockReturnValue(null)
vi.mock('@/utils/error-parser', () => ({
parsePluginErrorMessage: (...args: unknown[]) => mockParsePluginErrorMessage(...args),
}))
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-oauth-client-state.spec.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-oauth-client-state.spec.ts
index 8b7acba171a..b97fa2690d4 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-oauth-client-state.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-oauth-client-state.spec.ts
@@ -5,10 +5,10 @@ import type {
import { act, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
+import { createHttpError } from '@/service/http-error'
import {
AuthorizationStatusEnum,
ClientTypeEnum,
- getErrorMessage,
useOAuthClientState,
} from '../use-oauth-client-state'
@@ -113,43 +113,6 @@ vi.mock('@/app/notifications', () => ({
// Test Suites
// ============================================================================
-describe('getErrorMessage', () => {
- it('should extract message from Error instance', () => {
- const error = new Error('Test error message')
- expect(getErrorMessage(error, 'fallback')).toBe('Test error message')
- })
-
- it('should extract message from object with message property', () => {
- const error = { message: 'Object error message' }
- expect(getErrorMessage(error, 'fallback')).toBe('Object error message')
- })
-
- it('should return fallback when error is empty object', () => {
- expect(getErrorMessage({}, 'fallback')).toBe('fallback')
- })
-
- it('should return fallback when error.message is not a string', () => {
- expect(getErrorMessage({ message: 123 }, 'fallback')).toBe('fallback')
- })
-
- it('should return fallback when error.message is empty string', () => {
- expect(getErrorMessage({ message: '' }, 'fallback')).toBe('fallback')
- })
-
- it('should return fallback when error is null', () => {
- expect(getErrorMessage(null, 'fallback')).toBe('fallback')
- })
-
- it('should return fallback when error is undefined', () => {
- expect(getErrorMessage(undefined, 'fallback')).toBe('fallback')
- })
-
- it('should return fallback when error is a primitive', () => {
- expect(getErrorMessage('string error', 'fallback')).toBe('fallback')
- expect(getErrorMessage(123, 'fallback')).toBe('fallback')
- })
-})
-
describe('useOAuthClientState', () => {
const defaultParams = {
oauthConfig: createMockOAuthConfig(),
@@ -368,9 +331,12 @@ describe('useOAuthClientState', () => {
})
})
- it('should show error toast with error message on failure', () => {
+ it('shows the HTTP error message when removal fails', () => {
+ const error = createHttpError(new Response(null, { status: 403 }), {
+ message: 'Delete failed',
+ })
mockDeleteOAuth.mockImplementation((provider, { onError }) => {
- onError(new Error('Delete failed'))
+ onError(error)
})
const { result } = renderHook(() => useOAuthClientState(defaultParams))
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
index ba81f2879ed..c1ef6d13586 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
@@ -163,9 +163,9 @@ export const useCommonModalState = ({
properties,
},
{
- onError: async (error: unknown) => {
+ onError: (error: unknown) => {
const errorMessage =
- (await parsePluginErrorMessage(error)) ||
+ parsePluginErrorMessage(error) ||
t(($) => $['modal.errors.updateFailed'], { ns: 'pluginTrigger' })
console.error('Failed to update subscription builder:', error)
toast.error(errorMessage)
@@ -257,9 +257,9 @@ export const useCommonModalState = ({
toast.success(t(($) => $['modal.apiKey.verify.success'], { ns: 'pluginTrigger' }))
setCurrentStep(ApiKeyStep.Configuration)
},
- onError: async (error: unknown) => {
+ onError: (error: unknown) => {
const errorMessage =
- (await parsePluginErrorMessage(error)) ||
+ parsePluginErrorMessage(error) ||
t(($) => $['modal.apiKey.verify.error'], { ns: 'pluginTrigger' })
apiKeyCredentialsFormRef.current?.setFields([
{
@@ -297,9 +297,9 @@ export const useCommonModalState = ({
onClose()
refetch?.()
},
- onError: async (error: unknown) => {
+ onError: (error: unknown) => {
const errorMessage =
- (await parsePluginErrorMessage(error)) ||
+ parsePluginErrorMessage(error) ||
t(($) => $['subscription.createFailed'], { ns: 'pluginTrigger' })
toast.error(errorMessage)
},
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
index a9c3f29b939..34a8e8aa87f 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
@@ -16,6 +16,7 @@ import {
useInitiateTriggerOAuth,
useVerifyAndUpdateTriggerSubscriptionBuilder,
} from '@/service/use-triggers'
+import { getErrorMessage } from '@/utils/error-message'
export const AuthorizationStatusEnum = {
Pending: 'pending',
@@ -35,16 +36,6 @@ export type ClientTypeEnum = (typeof ClientTypeEnum)[keyof typeof ClientTypeEnum
const POLL_INTERVAL_MS = 3000
-// Extract error message from various error formats
-export const getErrorMessage = (error: unknown, fallback: string): string => {
- if (error instanceof Error && error.message) return error.message
- if (typeof error === 'object' && error && 'message' in error) {
- const message = (error as { message?: string }).message
- if (typeof message === 'string' && message) return message
- }
- return fallback
-}
-
type UseOAuthClientStateParams = {
oauthConfig?: TriggerOAuthConfig
providerName: string
@@ -148,10 +139,8 @@ export const useOAuthClientState = ({
},
onError: (error: unknown) => {
toast.error(
- getErrorMessage(
- error,
+ getErrorMessage(error) ??
t(($) => $['modal.oauth.remove.failed'], { ns: 'pluginTrigger' }),
- ),
)
},
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
index 5972eff565e..984786c17d1 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
@@ -577,11 +577,9 @@ describe('Edit Modal Components', () => {
})
})
- it('should use error.message from object when available', async () => {
+ it('should use error.message when available', async () => {
formValuesMap.set('main', { values: { subscription_name: 'Name' }, isCheckValidated: true })
- mockUpdateSubscription.mockImplementation((_p, cb) =>
- cb.onError({ message: 'Object error' }),
- )
+ mockUpdateSubscription.mockImplementation((_p, cb) => cb.onError(new Error('Object error')))
render(<ManualEditModal {...createProps()} />)
fireEvent.click(getConfirmButton())
await waitFor(() => {
@@ -1099,7 +1097,7 @@ describe('Edit Modal Components', () => {
it('should show error toast on verification failure', async () => {
formValuesMap.set('credentials', { values: { api_key: 'bad-key' }, isCheckValidated: true })
- mockParsePluginErrorMessage.mockResolvedValue('Invalid API key')
+ mockParsePluginErrorMessage.mockReturnValue('Invalid API key')
mockVerifyCredentials.mockImplementation((_p, cb) => cb.onError(new Error('Invalid')))
render(<ApiKeyEditModal {...createProps()} />)
fireEvent.click(getConfirmButton())
@@ -1115,7 +1113,7 @@ describe('Edit Modal Components', () => {
it('should use fallback error message when parsePluginErrorMessage returns null', async () => {
formValuesMap.set('credentials', { values: { api_key: 'bad-key' }, isCheckValidated: true })
- mockParsePluginErrorMessage.mockResolvedValue(null)
+ mockParsePluginErrorMessage.mockReturnValue(null)
mockVerifyCredentials.mockImplementation((_p, cb) => cb.onError(new Error('Invalid')))
render(<ApiKeyEditModal {...createProps()} />)
fireEvent.click(getConfirmButton())
@@ -1326,7 +1324,7 @@ describe('Edit Modal Components', () => {
values: { subscription_name: 'Name' },
isCheckValidated: true,
})
- mockParsePluginErrorMessage.mockResolvedValue('Update failed')
+ mockParsePluginErrorMessage.mockReturnValue('Update failed')
mockUpdateSubscription.mockImplementation((_p, cb) => cb.onError(new Error('Failed')))
render(<ApiKeyEditModal {...createProps()} />)
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
index 5c3cceb0323..ef1ce290311 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
@@ -169,9 +169,9 @@ export const ApiKeyEditModal = ({ onClose, subscription, pluginDetail }: Props)
setVerifiedCredentials(areAllCredentialsHidden(credentials) ? null : credentials)
setCurrentStep(EditStep.EditConfiguration)
},
- onError: async (error: unknown) => {
+ onError: (error: unknown) => {
const errorMessage =
- (await parsePluginErrorMessage(error)) ||
+ parsePluginErrorMessage(error) ||
t(($) => $['modal.apiKey.verify.error'], { ns: 'pluginTrigger' })
toast.error(errorMessage)
},
@@ -210,9 +210,9 @@ export const ApiKeyEditModal = ({ onClose, subscription, pluginDetail }: Props)
refetch?.()
onClose()
},
- onError: async (error: unknown) => {
+ onError: (error: unknown) => {
const errorMessage =
- (await parsePluginErrorMessage(error)) ||
+ parsePluginErrorMessage(error) ||
t(($) => $['subscription.list.item.actions.edit.error'], { ns: 'pluginTrigger' })
toast.error(errorMessage)
},
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
index b45df5ebfc4..20a6a0c259d 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
@@ -13,6 +13,7 @@ import { FormTypeEnum } from '@/app/components/base/form/types'
import { ReadmeEntrance } from '@/app/components/plugins/readme-panel/entrance'
import { toast } from '@/app/notifications'
import { useUpdateTriggerSubscription } from '@/service/use-triggers'
+import { getErrorMessage } from '@/utils/error-message'
import { usePluginStore } from '../../store'
import { useSubscriptionList } from '../use-subscription-list'
@@ -50,15 +51,6 @@ export const ManualEditModal = ({ onClose, subscription, pluginDetail }: Props)
const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription()
- const getErrorMessage = (error: unknown, fallback: string) => {
- if (error instanceof Error && error.message) return error.message
- if (typeof error === 'object' && error && 'message' in error) {
- const message = (error as { message?: string }).message
- if (typeof message === 'string' && message) return message
- }
- return fallback
- }
-
const propertiesSchema = useMemo<ParametersSchema[]>(
() => detail?.declaration?.trigger?.subscription_schema || [],
[detail?.declaration?.trigger?.subscription_schema],
@@ -96,10 +88,8 @@ export const ManualEditModal = ({ onClose, subscription, pluginDetail }: Props)
},
onError: (error: unknown) => {
toast.error(
- getErrorMessage(
- error,
+ getErrorMessage(error) ??
t(($) => $['subscription.list.item.actions.edit.error'], { ns: 'pluginTrigger' }),
- ),
)
},
},
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
index a31b815f655..9888f74af6f 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
@@ -13,6 +13,7 @@ import { FormTypeEnum } from '@/app/components/base/form/types'
import { ReadmeEntrance } from '@/app/components/plugins/readme-panel/entrance'
import { toast } from '@/app/notifications'
import { useUpdateTriggerSubscription } from '@/service/use-triggers'
+import { getErrorMessage } from '@/utils/error-message'
import { usePluginStore } from '../../store'
import { useSubscriptionList } from '../use-subscription-list'
@@ -50,15 +51,6 @@ export const OAuthEditModal = ({ onClose, subscription, pluginDetail }: Props) =
const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription()
- const getErrorMessage = (error: unknown, fallback: string) => {
- if (error instanceof Error && error.message) return error.message
- if (typeof error === 'object' && error && 'message' in error) {
- const message = (error as { message?: string }).message
- if (typeof message === 'string' && message) return message
- }
- return fallback
- }
-
const parametersSchema = useMemo<ParametersSchema[]>(
() => detail?.declaration?.trigger?.subscription_constructor?.parameters || [],
[detail?.declaration?.trigger?.subscription_constructor?.parameters],
@@ -96,10 +88,8 @@ export const OAuthEditModal = ({ onClose, subscription, pluginDetail }: Props) =
},
onError: (error: unknown) => {
toast.error(
- getErrorMessage(
- error,
+ getErrorMessage(error) ??
t(($) => $['subscription.list.item.actions.edit.error'], { ns: 'pluginTrigger' }),
- ),
)
},
},
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
index f3c13e91d85..59a4a008f83 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,6 +1,7 @@
import { renderHook } from '@testing-library/react'
import { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
const mockGetNodes = vi.fn()
@@ -421,10 +422,9 @@ describe('useNodesSyncDraft', () => {
{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
])
- const mockJsonError = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }),
- bodyUsed: false,
- }
+ const mockJsonError = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_sync',
+ })
mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)
const { result } = renderHook(() => useNodesSyncDraft())
@@ -444,10 +444,9 @@ describe('useNodesSyncDraft', () => {
{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
])
- const mockJsonError = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }),
- bodyUsed: false,
- }
+ const mockJsonError = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_sync',
+ })
mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)
const { result } = renderHook(() => useNodesSyncDraft())
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
index 5d9cfee9977..defe8010f82 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
@@ -1,5 +1,6 @@
import { renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import { usePipelineInit } from '../use-pipeline-init'
const mockWorkflowStoreGetState = vi.fn()
@@ -269,10 +270,9 @@ describe('usePipelineInit', () => {
describe('draft not exist error handling', () => {
it('should create initial workflow when draft does not exist', async () => {
- const mockJsonError = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_exist' }),
- bodyUsed: false,
- }
+ const mockJsonError = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_exist',
+ })
mockFetchWorkflowDraft.mockRejectedValueOnce(mockJsonError)
mockSyncWorkflowDraft.mockResolvedValue({ updated_at: '2024-01-02T00:00:00Z' })
@@ -296,10 +296,9 @@ describe('usePipelineInit', () => {
})
it('should sync initial workflow with template nodes', async () => {
- const mockJsonError = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_exist' }),
- bodyUsed: false,
- }
+ const mockJsonError = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_exist',
+ })
mockFetchWorkflowDraft.mockRejectedValueOnce(mockJsonError)
mockSyncWorkflowDraft.mockResolvedValue({ updated_at: '2024-01-02T00:00:00Z' })
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
index fd8c20bfd79..847702e82be 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
@@ -1,6 +1,7 @@
import { act, renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
+import { httpErrorFromResponse } from '@/service/http-error'
import { useUpdateDSLModal } from '../use-update-dsl-modal'
class MockFileReader {
@@ -385,14 +386,16 @@ describe('useUpdateDSLModal', () => {
it('should notify response error when importDSL rejects with a response body', async () => {
mockImportDSL.mockRejectedValue(
- new Response(
- JSON.stringify({
- error: 'Missing rag_pipeline data in YAML content',
- }),
- {
- status: 400,
- headers: { 'Content-Type': 'application/json' },
- },
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ error: 'Missing rag_pipeline data in YAML content',
+ }),
+ {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
),
)
@@ -541,14 +544,16 @@ describe('useUpdateDSLModal', () => {
it('should notify response error when confirm rejects with a response body', async () => {
mockImportDSLConfirm.mockRejectedValue(
- new Response(
- JSON.stringify({
- error: 'Import information expired or does not exist',
- }),
- {
- status: 400,
- headers: { 'Content-Type': 'application/json' },
- },
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ error: 'Import information expired or does not exist',
+ }),
+ {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
),
)
diff --git a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
index 92cbf061634..65fb276be7b 100644
--- a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
@@ -1,4 +1,5 @@
import type { SyncDraftCallback } from '@/app/components/workflow/hooks-store'
+import { ORPCError } from '@orpc/client'
import { produce } from 'immer'
import { useCallback } from 'react'
import { useStoreApi } from 'reactflow'
@@ -92,12 +93,12 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
setDraftUpdatedAt(res.updated_at)
callback?.onSuccess?.()
} catch (error: any) {
- if (error && error.json && !error.bodyUsed) {
- error.json().then((err: any) => {
- if (err.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)
- handleRefreshWorkflowDraft()
- })
- }
+ if (
+ error instanceof ORPCError &&
+ error.code === 'draft_workflow_not_sync' &&
+ !notRefreshWhenSyncError
+ )
+ handleRefreshWorkflowDraft()
callback?.onError?.()
} finally {
callback?.onSettled?.()
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
index 81bc6dcdedc..ecfd5ee0a91 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
@@ -1,4 +1,5 @@
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
+import { ORPCError } from '@orpc/client'
import { useCallback, useEffect, useState } from 'react'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
@@ -56,29 +57,27 @@ export const usePipelineInit = () => {
workflowStore.setState({ isWorkflowDataLoaded: true })
setIsLoading(false)
} catch (error: any) {
- if (error && error.json && !error.bodyUsed && datasetId) {
- error.json().then((err: any) => {
- if (err.code === 'draft_workflow_not_exist') {
- workflowStore.setState({
- notInitialWorkflow: true,
- shouldAutoOpenStartNodeSelector: true,
- })
- syncWorkflowDraft({
- url: `/rag/pipelines/${datasetId}/workflows/draft`,
- params: {
- graph: {
- nodes: nodesTemplate,
- edges: edgesTemplate,
- },
- environment_variables: [],
+ if (error instanceof ORPCError && datasetId) {
+ if (error.code === 'draft_workflow_not_exist') {
+ workflowStore.setState({
+ notInitialWorkflow: true,
+ shouldAutoOpenStartNodeSelector: true,
+ })
+ syncWorkflowDraft({
+ url: `/rag/pipelines/${datasetId}/workflows/draft`,
+ params: {
+ graph: {
+ nodes: nodesTemplate,
+ edges: edgesTemplate,
},
- }).then((res) => {
- const { setDraftUpdatedAt } = workflowStore.getState()
- setDraftUpdatedAt(res.updated_at)
- handleGetInitialWorkflowData()
- })
- }
- })
+ environment_variables: [],
+ },
+ }).then((res) => {
+ const { setDraftUpdatedAt } = workflowStore.getState()
+ setDraftUpdatedAt(res.updated_at)
+ handleGetInitialWorkflowData()
+ })
+ }
}
}
}, [nodesTemplate, edgesTemplate, workflowStore, datasetId])
diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
index f601fbe9ae5..0815e7d8c7a 100644
--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
+++ b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
@@ -10,39 +10,18 @@ import { useEventEmitterContextContext } from '@/context/event-emitter'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
import { useImportPipelineDSL, useImportPipelineDSLConfirm } from '@/service/use-pipeline'
import { fetchWorkflowDraft } from '@/service/workflow'
+import { getErrorMessage } from '@/utils/error-message'
type VersionInfo = {
importedVersion: string
systemVersion: string
}
-type ImportErrorResponse = {
- message?: unknown
- error?: unknown
-}
type UseUpdateDSLModalParams = {
onCancel: () => void
onImport?: () => void
}
const isCompletedStatus = (status: DSLImportStatus): boolean =>
status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS
-const getNonEmptyString = (value: unknown): string | undefined => {
- if (typeof value !== 'string') return undefined
-
- const trimmedValue = value.trim()
- return trimmedValue || undefined
-}
-const getImportErrorMessage = async (error: unknown): Promise<string | undefined> => {
- if (error instanceof Response && !error.bodyUsed) {
- try {
- const errorData = (await error.clone().json()) as ImportErrorResponse
- return getNonEmptyString(errorData.message) ?? getNonEmptyString(errorData.error)
- } catch {}
- }
-
- if (error instanceof Error) return getNonEmptyString(error.message)
-
- return undefined
-}
export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParams) => {
const { t } = useTranslation(['workflow'])
const { eventEmitter } = useEventEmitterContextContext()
@@ -154,7 +133,7 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
showVersionMismatch(id, imported_dsl_version, current_dsl_version)
else notifyError(response.error)
} catch (error) {
- notifyError(await getImportErrorMessage(error))
+ notifyError(getErrorMessage(error)?.trim() || undefined)
}
isCreatingRef.current = false
}, [
@@ -176,7 +155,7 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
}
if (status === DSLImportStatus.FAILED) notifyError(error)
} catch (error) {
- notifyError(await getImportErrorMessage(error))
+ notifyError(getErrorMessage(error)?.trim() || undefined)
}
}, [importId, importDSLConfirm, completeImport, notifyError])
return {
diff --git a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
index 03a1fb79126..62df5941d77 100644
--- a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
+++ b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
@@ -1,5 +1,6 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { httpErrorFromResponse } from '@/service/http-error'
import { render } from '@/test/console/render'
import ImportSnippetDSLDialog from '../import-snippet-dsl-dialog'
@@ -151,6 +152,30 @@ describe('ImportSnippetDSLDialog', () => {
})
})
+ it.each(['import', 'confirm'])('leaves HTTP %s failures to the request layer', async (step) => {
+ const user = userEvent.setup()
+ const onClose = vi.fn()
+ const error = await httpErrorFromResponse(
+ Response.json({ message: 'Invalid DSL' }, { status: 400 }),
+ )
+ if (step === 'import') serviceMocks.importMutateAsync.mockRejectedValue(error)
+ else {
+ serviceMocks.importMutateAsync.mockResolvedValue({ id: 'import-1', status: 'pending' })
+ serviceMocks.confirmMutateAsync.mockRejectedValue(error)
+ }
+
+ render(<ImportSnippetDSLDialog isOpen onClose={onClose} />)
+ await user.click(screen.getByRole('button', { name: 'select-dsl-file' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
+ if (step === 'confirm') {
+ await user.click(await screen.findByRole('button', { name: 'common.operation.confirm' }))
+ expect(serviceMocks.confirmMutateAsync).toHaveBeenCalledWith({ importId: 'import-1' })
+ }
+ expect(serviceMocks.importMutateAsync).toHaveBeenCalledOnce()
+ expect(toastMocks.error).not.toHaveBeenCalled()
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
it('should disable import without snippet create permission', async () => {
const user = userEvent.setup()
contextMocks.workspacePermissionKeys = []
diff --git a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 5a328dff6fe..4d1e5dae6b4 100644
--- a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,9 +1,11 @@
import type { SnippetInputField } from '@/models/snippet'
+import { ORPCError } from '@orpc/client'
import { act, renderHook } from '@testing-library/react'
import { PipelineInputVarType } from '@/models/pipeline'
import { useSnippetDraftStore } from '../../draft-store'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
+const mockRefreshDraft = vi.fn()
const mockGetNodes = vi.fn()
const mockGetNodesReadOnly = vi.fn()
const mockUseNodesReadOnlyByCanEdit = vi.fn()
@@ -80,7 +82,7 @@ vi.mock('@/config', () => ({ API_PREFIX: '/api' }))
vi.mock('../use-snippet-refresh-draft', () => ({
useSnippetRefreshDraft: () => ({
- handleRefreshWorkflowDraft: vi.fn(),
+ handleRefreshWorkflowDraft: mockRefreshDraft,
}),
}))
@@ -121,6 +123,43 @@ describe('snippet/use-nodes-sync-draft', () => {
useSnippetDraftStore.getState().setInputFields([createInputField('topic')])
})
+ it.each([
+ { code: 'draft_workflow_not_sync', skipRefresh: false, refreshes: 1 },
+ { code: 'draft_workflow_not_sync', skipRefresh: true, refreshes: 0 },
+ { code: 'forbidden', skipRefresh: false, refreshes: 0 },
+ ])(
+ 'recovers from $code with skipRefresh=$skipRefresh and allows retry',
+ async ({ code, skipRefresh, refreshes }) => {
+ mockSyncDraftWorkflow.mockRejectedValueOnce(
+ new ORPCError(code, {
+ status: code === 'forbidden' ? 403 : 409,
+ message: 'Draft could not be saved',
+ }),
+ )
+ const callback = { onError: vi.fn(), onSuccess: vi.fn(), onSettled: vi.fn() }
+ const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
+
+ await act(async () => {
+ expect(await result.current.doSyncWorkflowDraft(skipRefresh, callback)).toBeUndefined()
+ })
+
+ expect(mockRefreshDraft).toHaveBeenCalledTimes(refreshes)
+ expect(callback.onError).toHaveBeenCalledOnce()
+ expect(callback.onSuccess).not.toHaveBeenCalled()
+ expect(callback.onSettled).toHaveBeenCalledOnce()
+ expect(mockSetSyncWorkflowDraftHash).not.toHaveBeenCalled()
+ expect(useSnippetDraftStore.getState().inputFields).toEqual([createInputField('topic')])
+
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callback)
+ })
+
+ expect(callback.onSuccess).toHaveBeenCalledOnce()
+ expect(callback.onSettled).toHaveBeenCalledTimes(2)
+ expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('next-hash')
+ },
+ )
+
it('should include current input_fields when syncing the draft graph', async () => {
const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
diff --git a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts b/web/app/components/snippets/hooks/use-nodes-sync-draft.ts
index f3b69a03755..38556c5d5c1 100644
--- a/web/app/components/snippets/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/snippets/hooks/use-nodes-sync-draft.ts
@@ -5,6 +5,7 @@ import type {
SnippetDraftSyncResponse,
SnippetWorkflow,
} from '@/types/snippet'
+import { ORPCError } from '@orpc/client'
import { produce } from 'immer'
import { useCallback } from 'react'
import { useStoreApi } from 'reactflow'
@@ -17,18 +18,6 @@ import { postWithKeepalive } from '@/service/fetch'
import { useSnippetDraftStore } from '../draft-store'
import { useSnippetRefreshDraft } from './use-snippet-refresh-draft'
-const isSyncConflictError = (
- error: unknown,
-): error is { bodyUsed: boolean; json: () => Promise<{ code?: string }> } => {
- return (
- !!error &&
- typeof error === 'object' &&
- 'bodyUsed' in error &&
- 'json' in error &&
- typeof error.json === 'function'
- )
-}
-
type SyncInputFieldsDraftCallback = SyncDraftCallback & {
onRefresh?: (inputFields: SnippetInputField[]) => void
}
@@ -129,12 +118,12 @@ export const useNodesSyncDraft = (snippetId: string) => {
callback?.onSuccess?.()
return response
} catch (error: unknown) {
- if (isSyncConflictError(error) && !error.bodyUsed) {
- error.json().then((err) => {
- if (err.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)
- handleRefreshWorkflowDraft(onRefresh)
- })
- }
+ if (
+ error instanceof ORPCError &&
+ error.code === 'draft_workflow_not_sync' &&
+ !notRefreshWhenSyncError
+ )
+ handleRefreshWorkflowDraft(onRefresh)
callback?.onError?.()
return undefined
} finally {
diff --git a/web/app/components/snippets/hooks/use-snippet-init.ts b/web/app/components/snippets/hooks/use-snippet-init.ts
index c5ff0c99899..8e48bbee2f1 100644
--- a/web/app/components/snippets/hooks/use-snippet-init.ts
+++ b/web/app/components/snippets/hooks/use-snippet-init.ts
@@ -2,6 +2,7 @@ import type { SnippetWorkflow } from '@/types/snippet'
import isEqual from 'fast-deep-equal'
import { useEffect, useMemo, useState } from 'react'
import { useWorkflowStore } from '@/app/components/workflow/store'
+import { isNotFoundError } from '@/service/http-error'
import {
fetchSnippetDraftWorkflow,
useSnippetDefaultBlockConfigs,
@@ -32,10 +33,6 @@ const normalizeNodesDefaultConfigs = (nodesDefaultConfigs: unknown) => {
)
}
-const isNotFoundError = (error: unknown) => {
- return !!error && typeof error === 'object' && 'status' in error && error.status === 404
-}
-
const getComparableWorkflowData = (workflow?: SnippetWorkflow | null) => {
return {
graph: workflow?.graph ?? {},
diff --git a/web/app/components/snippets/import-snippet-dsl-dialog.tsx b/web/app/components/snippets/import-snippet-dsl-dialog.tsx
index 8ca622b46a7..6c2a72fa750 100644
--- a/web/app/components/snippets/import-snippet-dsl-dialog.tsx
+++ b/web/app/components/snippets/import-snippet-dsl-dialog.tsx
@@ -15,6 +15,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Input } from '@langgenius/dify-ui/input'
import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
+import { ORPCError } from '@orpc/client'
import { useAtomValue } from 'jotai'
import { useCallback, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -188,7 +189,9 @@ function ImportSnippetDSLDialog({ isOpen, onClose }: ImportSnippetDSLDialogProps
handleImportResponse(response)
} catch (error) {
- if (error instanceof Error && error.message) toast.error(error.message)
+ // HTTP error notifications are owned by the request layer.
+ if (!(error instanceof ORPCError) && error instanceof Error && error.message)
+ toast.error(error.message)
}
}, [
canCreateAndModifySnippet,
@@ -206,7 +209,9 @@ function ImportSnippetDSLDialog({ isOpen, onClose }: ImportSnippetDSLDialogProps
const response = await confirmSnippetImportMutation.mutateAsync({ importId })
handleImportResponse(response)
} catch (error) {
- if (error instanceof Error && error.message) toast.error(error.message)
+ // HTTP error notifications are owned by the request layer.
+ if (!(error instanceof ORPCError) && error instanceof Error && error.message)
+ toast.error(error.message)
}
}, [canCreateAndModifySnippet, confirmSnippetImportMutation, handleImportResponse, importId])
diff --git a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
index 2396c324f06..a224250aaba 100644
--- a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
+++ b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
@@ -1,8 +1,10 @@
import type { EmojiIcon, ImageIcon } from '@/app/components/base/icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { act, renderHook } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vite-plus/test'
+import { afterEach, describe, expect, it, vi } from 'vite-plus/test'
import { MCPAuthMethod } from '@/app/components/tools/types'
+import { toast } from '@/app/notifications'
+import { createHttpError } from '@/service/http-error'
import { isValidServerID, isValidUrl, useMCPModalForm } from '../use-mcp-modal-form'
// Mock the API service
@@ -20,6 +22,10 @@ vi.mock('tldts', () => ({
}),
}))
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
describe('useMCPModalForm', () => {
describe('Utility Functions', () => {
describe('isValidUrl', () => {
@@ -408,50 +414,32 @@ describe('useMCPModalForm', () => {
})
})
- it('should handle error when icon fetch fails with error code', async () => {
- const { uploadRemoteFileInfo } = await import('@/service/common')
- const mockError = {
- json: vi.fn().mockResolvedValue({ code: 'UPLOAD_ERROR' }),
- }
- vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(mockError)
-
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
-
- const { result } = renderHook(() => useMCPModalForm())
-
- await act(async () => {
- await result.current.actions.handleUrlBlur('https://example.com/mcp')
- })
-
- // Should have called console.error
- expect(consoleErrorSpy).toHaveBeenCalled()
- // isFetchingIcon should be reset to false after error
- expect(result.current.state.isFetchingIcon).toBe(false)
-
- consoleErrorSpy.mockRestore()
- })
-
- it('should handle error when icon fetch fails without error code', async () => {
+ it.each([
+ {
+ name: 'HTTP failure',
+ error: createHttpError(new Response(null, { status: 400 }), {
+ code: 'UPLOAD_ERROR',
+ message: 'Remote icon upload failed',
+ }),
+ message: 'Remote icon upload failed',
+ },
+ {
+ name: 'network failure',
+ error: new TypeError('Failed to fetch'),
+ message: 'Failed to fetch',
+ },
+ ])('shows the error message for an icon $name', async ({ error, message }) => {
const { uploadRemoteFileInfo } = await import('@/service/common')
- const mockError = {
- json: vi.fn().mockResolvedValue({}),
- }
- vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(mockError)
-
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
-
+ vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(error)
+ const warningSpy = vi.spyOn(toast, 'warning').mockReturnValue('icon-upload-warning')
const { result } = renderHook(() => useMCPModalForm())
await act(async () => {
await result.current.actions.handleUrlBlur('https://example.com/mcp')
})
- // Should have called console.error
- expect(consoleErrorSpy).toHaveBeenCalled()
- // isFetchingIcon should be reset to false after error
+ expect(warningSpy).toHaveBeenCalledWith(message)
expect(result.current.state.isFetchingIcon).toBe(false)
-
- consoleErrorSpy.mockRestore()
})
it('should ignore stale blur when a newer blur starts before fetch completes', async () => {
diff --git a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
index 43b6e63e217..54e427ca770 100644
--- a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
+++ b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
@@ -136,14 +136,7 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
if (isStale()) return
let errorMessage = 'Failed to fetch remote icon'
- if (e instanceof Response) {
- try {
- const errorData = await e.json()
- if (errorData?.code) errorMessage = `Upload failed: ${errorData.code}`
- } catch {
- // Ignore JSON parsing errors
- }
- } else if (e instanceof Error) {
+ if (e instanceof Error) {
errorMessage = e.message
}
console.error('Failed to fetch remote icon:', e)
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts
index 7ea63f2f803..157f1c488c6 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts
@@ -4,6 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import { createElement } from 'react'
import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'
import { consoleQuery } from '@/service/console'
+import { httpErrorFromResponse } from '@/service/http-error'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { useDSLByCanEdit } from '../use-DSL'
@@ -297,7 +298,11 @@ workflow:
it('should notify when export fails', async () => {
mockExportAppConfig.mockRejectedValue(
- new Response(JSON.stringify({ message: 'Package contains unusable Skill' }), { status: 500 }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ message: 'Package contains unusable Skill' }), {
+ status: 500,
+ }),
+ ),
)
const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
index a1fc11ae607..2dc5c2af0e5 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { BlockEnum } from '@/app/components/workflow/types'
import { markAppDeletionFailed, markAppDeletionStarted } from '@/service/app-deletion'
import { consoleQuery } from '@/service/console'
+import { createHttpError } from '@/service/http-error'
import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { AppModeEnum } from '@/types/app'
@@ -593,10 +594,9 @@ describe('useNodesSyncDraft', () => {
})
it('should call handleRefreshWorkflowDraft(true) — not updating canvas — on draft_workflow_not_sync', async () => {
- const error = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }),
- bodyUsed: false,
- }
+ const error = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_sync',
+ })
mockSyncWorkflowDraft.mockRejectedValue(error)
const { result } = renderUseNodesSyncDraft()
@@ -609,10 +609,9 @@ describe('useNodesSyncDraft', () => {
})
it('should NOT refresh when notRefreshWhenSyncError=true', async () => {
- const error = {
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }),
- bodyUsed: false,
- }
+ const error = createHttpError(new Response(null, { status: 400 }), {
+ code: 'draft_workflow_not_sync',
+ })
mockSyncWorkflowDraft.mockRejectedValue(error)
const { result } = renderUseNodesSyncDraft()
@@ -625,7 +624,7 @@ describe('useNodesSyncDraft', () => {
})
it('should NOT refresh for a different error code', async () => {
- const error = { json: vi.fn().mockResolvedValue({ code: 'other_error' }), bodyUsed: false }
+ const error = createHttpError(new Response(null, { status: 400 }), { code: 'other_error' })
mockSyncWorkflowDraft.mockRejectedValue(error)
const { result } = renderUseNodesSyncDraft()
@@ -638,10 +637,7 @@ describe('useNodesSyncDraft', () => {
})
it('should ignore non-JSON sync errors without throwing an unhandled rejection', async () => {
- const error = {
- json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected token U')),
- bodyUsed: false,
- }
+ const error = createHttpError(new Response(null, { status: 502 }))
const callbacks = {
onError: vi.fn(),
onSettled: vi.fn(),
@@ -653,7 +649,6 @@ describe('useNodesSyncDraft', () => {
await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
})
- expect(error.json).toHaveBeenCalled()
expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
expect(callbacks.onError).toHaveBeenCalled()
expect(callbacks.onSettled).toHaveBeenCalled()
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
index 6918bacaecf..c8b9a17e9df 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
@@ -1,6 +1,7 @@
import { waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { BlockEnum } from '@/app/components/workflow/types'
+import { createHttpError } from '@/service/http-error'
import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'
import { renderHook as renderHookWithConsoleState } from '@/test/console/render'
import { AppACLPermission } from '@/utils/permission'
@@ -92,10 +93,8 @@ vi.mock('@/service/workflow', () => ({
fetchNodesDefaultConfigs: (...args: unknown[]) => mockFetchNodesDefaultConfigs(...args),
}))
-const notExistError = () => ({
- json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_exist' }),
- bodyUsed: false,
-})
+const notExistError = () =>
+ createHttpError(new Response(null, { status: 400 }), { code: 'draft_workflow_not_exist' })
const draftResponse = {
id: 'draft-id',
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts
index 6aa174ba034..b88fea15858 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts
@@ -1,5 +1,6 @@
import { TriggerType } from '@/app/components/workflow/header/test-run-menu'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { httpErrorFromResponse } from '@/service/http-error'
import { AppModeEnum } from '@/types/app'
import {
applyRunningStateForMode,
@@ -447,7 +448,7 @@ describe('useWorkflowRun utils', () => {
expect(setWorkflowRunningData).not.toHaveBeenCalled()
})
- it('should handle Response and non-Response trigger debug exceptions correctly', async () => {
+ it('should report both HTTP and network trigger debug failures', async () => {
const clearAbortController = vi.fn()
const clearListeningStateSpy = vi.fn()
const setAbortController = vi.fn()
@@ -455,9 +456,12 @@ describe('useWorkflowRun utils', () => {
const controllerTarget: Record<string, unknown> = {}
mockPost.mockRejectedValueOnce(
- new Response(JSON.stringify({ error: 'Plugin failed' }), {
- headers: { 'content-type': 'application/json' },
- }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ error: 'Plugin failed' }), {
+ status: 500,
+ headers: { 'content-type': 'application/json' },
+ }),
+ ),
)
await runTriggerDebug({
@@ -491,8 +495,11 @@ describe('useWorkflowRun utils', () => {
setWorkflowRunningData,
})
- expect(clearAbortController).toHaveBeenCalledTimes(1)
- expect(setWorkflowRunningData).toHaveBeenCalledTimes(1)
+ expect(mockToastError).toHaveBeenLastCalledWith('network failed')
+ expect(clearAbortController).toHaveBeenCalledTimes(2)
+ expect(setWorkflowRunningData).toHaveBeenLastCalledWith(
+ createFailedWorkflowState('network failed'),
+ )
expect(clearListeningStateSpy).toHaveBeenCalledTimes(2)
})
diff --git a/web/app/components/workflow-app/hooks/use-DSL.ts b/web/app/components/workflow-app/hooks/use-DSL.ts
index 3d4ddcb2e67..9f3fe7c2e0e 100644
--- a/web/app/components/workflow-app/hooks/use-DSL.ts
+++ b/web/app/components/workflow-app/hooks/use-DSL.ts
@@ -3,13 +3,13 @@ import type { ExportSecretEnvironmentEvent } from '@/app/components/workflow/exp
import { useMutation, useQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'
import { exportAppDslFile } from '@/app/components/app/use-export-app-dsl'
import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'
import { toast } from '@/app/notifications'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { useParams } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'
type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']
@@ -61,7 +61,7 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
} catch (error) {
toast.error(
t(($) => $.exportAppFailed, { ns: 'app' }),
- { description: await getAppTransferErrorMessage(error) },
+ { description: getErrorMessage(error) },
)
return false
}
@@ -91,7 +91,7 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
toast.error(
t(($) => $.exportAppFailed, { ns: 'app' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
}
diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
index 05984fee362..e595fe9ed06 100644
--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
@@ -4,6 +4,7 @@ import type {
SyncDraftResult,
} from '@/app/components/workflow/hooks-store'
import type { WorkflowDraftFeaturesPayload } from '@/service/workflow'
+import { ORPCError } from '@orpc/client'
import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback, useEffect, useRef } from 'react'
@@ -228,19 +229,12 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
const { appId, isWorkflowDataLoaded } = workflowStore.getState()
if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) return null
- const responseError = error as {
- bodyUsed?: boolean
- json?: () => Promise<{ code?: string }>
- }
- if (responseError.json && !responseError.bodyUsed) {
- try {
- const err = await responseError.json()
- if (err.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)
- handleRefreshWorkflowDraft(true)
- } catch {
- // Non-JSON upstream errors should not surface as unhandled promise rejections.
- }
- }
+ if (
+ error instanceof ORPCError &&
+ error.code === 'draft_workflow_not_sync' &&
+ !notRefreshWhenSyncError
+ )
+ handleRefreshWorkflowDraft(true)
callback?.onError?.()
return null
} finally {
diff --git a/web/app/components/workflow-app/hooks/use-workflow-init.ts b/web/app/components/workflow-app/hooks/use-workflow-init.ts
index 1e6037e8405..de08d5c7478 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-init.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-init.ts
@@ -1,6 +1,7 @@
import type { Edge, Node } from '@/app/components/workflow/types'
import type { FileUploadConfigResponse } from '@/models/common'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
+import { ORPCError } from '@orpc/client'
import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useCallback, useEffect, useMemo, useState } from 'react'
@@ -126,62 +127,56 @@ export const useWorkflowInit = () => {
setSyncWorkflowDraftHash(initialData.hash)
setIsLoading(false)
} catch (error: unknown) {
- const responseError = error as {
- bodyUsed?: boolean
- json?: () => Promise<{ code?: string }>
- }
- if (responseError.json && !responseError.bodyUsed && appDetail) {
- responseError.json().then((err) => {
- if (err.code === 'draft_workflow_not_exist') {
- const isAdvancedChat = appDetail.mode === AppModeEnum.ADVANCED_CHAT
- const initialGraph = {
- nodes: isAdvancedChat ? nodesTemplate : [],
- edges: isAdvancedChat ? edgesTemplate : [],
- }
+ if (error instanceof ORPCError && appDetail) {
+ if (error.code === 'draft_workflow_not_exist') {
+ const isAdvancedChat = appDetail.mode === AppModeEnum.ADVANCED_CHAT
+ const initialGraph = {
+ nodes: isAdvancedChat ? nodesTemplate : [],
+ edges: isAdvancedChat ? edgesTemplate : [],
+ }
+ workflowStore.setState({
+ notInitialWorkflow: true,
+ showOnboarding: false,
+ shouldAutoOpenStartNodeSelector: false,
+ hasSelectedStartNode: false,
+ hasShownOnboarding: !isAdvancedChat,
+ })
+
+ if (!appACLCapabilities.canEdit) {
+ const initialData = createLocalWorkflowDraft({
+ ...getWorkflowDraftGraphForCanvas(initialGraph, {
+ localStartPlaceholderNodes: nodesTemplate,
+ }),
+ viewport: undefined,
+ })
+ setData(initialData)
workflowStore.setState({
- notInitialWorkflow: true,
- showOnboarding: false,
- shouldAutoOpenStartNodeSelector: false,
- hasSelectedStartNode: false,
- hasShownOnboarding: !isAdvancedChat,
+ envSecrets: {},
+ environmentVariables: [],
+ conversationVariables: [],
+ isWorkflowDataLoaded: true,
})
+ setSyncWorkflowDraftHash(initialData.hash)
+ setIsLoading(false)
+ return
+ }
- if (!appACLCapabilities.canEdit) {
- const initialData = createLocalWorkflowDraft({
- ...getWorkflowDraftGraphForCanvas(initialGraph, {
- localStartPlaceholderNodes: nodesTemplate,
- }),
- viewport: undefined,
- })
- setData(initialData)
- workflowStore.setState({
- envSecrets: {},
- environmentVariables: [],
- conversationVariables: [],
- isWorkflowDataLoaded: true,
- })
- setSyncWorkflowDraftHash(initialData.hash)
- setIsLoading(false)
- return
- }
-
- syncWorkflowDraft({
- url: `/apps/${appDetail.id}/workflows/draft`,
- params: {
- graph: initialGraph,
- force: true,
- features: {
- retriever_resource: { enabled: true },
- },
- conversation_variables: [],
+ syncWorkflowDraft({
+ url: `/apps/${appDetail.id}/workflows/draft`,
+ params: {
+ graph: initialGraph,
+ force: true,
+ features: {
+ retriever_resource: { enabled: true },
},
- }).then((res) => {
- workflowStore.getState().setDraftUpdatedAt(res.updated_at)
- setSyncWorkflowDraftHash(res.hash)
- handleGetInitialWorkflowData()
- })
- }
- })
+ conversation_variables: [],
+ },
+ }).then((res) => {
+ workflowStore.getState().setDraftUpdatedAt(res.updated_at)
+ setSyncWorkflowDraftHash(res.hash)
+ handleGetInitialWorkflowData()
+ })
+ }
}
}
}, [
diff --git a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts b/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
index 1029fabb0e0..e30266c0380 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
@@ -453,9 +453,8 @@ export const runTriggerDebug = async ({
} catch (error) {
if (controller.signal.aborted) return
- if (error instanceof Response) {
- const data = (await error.clone().json()) as Record<string, unknown>
- const errorMessage = typeof data?.error === 'string' ? data.error : ''
+ if (error instanceof Error) {
+ const errorMessage = error.message
toast.error(errorMessage)
clearAbortController()
setWorkflowRunningData(createFailedWorkflowState(errorMessage))
diff --git a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
index 34a474e724b..950b7a0f029 100644
--- a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
+++ b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
@@ -7,6 +7,7 @@ import userEvent from '@testing-library/user-event'
import { toast } from '@/app/notifications'
import { EventEmitterContext } from '@/context/event-emitter'
import { DSLImportStatus } from '@/models/app'
+import { httpErrorFromResponse } from '@/service/http-error'
import UpdateDSLModal from '../update-dsl-modal'
const mockEmit = vi.fn()
@@ -582,7 +583,9 @@ describe('UpdateDSLModal', () => {
it('should show an error notification when import throws', async () => {
mockImportDSL.mockRejectedValue(
- Response.json({ message: 'Invalid app package' }, { status: 400 }),
+ await httpErrorFromResponse(
+ Response.json({ message: 'Invalid app package' }, { status: 400 }),
+ ),
)
renderModal()
@@ -658,7 +661,9 @@ describe('UpdateDSLModal', () => {
current_dsl_version: '2.0.0',
})
mockImportDSLConfirm.mockRejectedValue(
- Response.json({ message: 'Invalid app package' }, { status: 400 }),
+ await httpErrorFromResponse(
+ Response.json({ message: 'Invalid app package' }, { status: 400 }),
+ ),
)
renderModal()
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
index 17cb1ddbb40..b9d4469cdbc 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
@@ -1,5 +1,6 @@
import { act, render, screen } from '@testing-library/react'
import { NodeRunningStatus } from '@/app/components/workflow/types'
+import { createHttpError } from '@/service/http-error'
import LastRun from '../index'
const mockUseHooksStore = vi.hoisted(() => vi.fn())
@@ -113,7 +114,7 @@ describe('LastRun', () => {
mockUseLastRun.mockReturnValue({
data: undefined,
isFetching: false,
- error: { status: 404 },
+ error: createHttpError(new Response(null, { status: 404 })),
})
render(
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx
index f1efd30fe52..489c9ade710 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx
@@ -1,4 +1,5 @@
'use client'
+
import type { FC } from 'react'
import type { ResultPanelProps } from '@/app/components/workflow/run/result-panel'
import type { NodeTracing } from '@/types/workflow'
@@ -8,6 +9,7 @@ import { useCallback, useEffect, useState } from 'react'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
import ResultPanel from '@/app/components/workflow/run/result-panel'
import { NodeRunningStatus } from '@/app/components/workflow/types'
+import { isNotFoundError } from '@/service/http-error'
import { useLastRun } from '@/service/use-workflow'
import { FlowType } from '@/types/common'
import NoData from './no-data'
@@ -80,7 +82,7 @@ const LastRun: FC<Props> = ({
? !hasAuthoritativeLastRun && activeStatuses.includes(oneStepRunRunningStatus!)
: isFetching)
- const noLastRun = (error as any)?.status === 404
+ const noLastRun = isNotFoundError(error)
const runResult = (canRunLastRun ? lastRunResult : singleRunResult) || lastRunResult || {}
let resolvedStatus = (runResult as any).status || otherResultPanelProps.status
diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
index 2eb7039455b..4b30f53ab70 100644
--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
@@ -1,5 +1,9 @@
-import { renderHook } from '@testing-library/react'
+import { ORPCError } from '@orpc/client'
+import { act, renderHook } from '@testing-library/react'
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
+import { toast } from '@/app/notifications'
+// oxlint-disable-next-line no-restricted-imports -- Mock the request boundary while preserving the single-run error owner.
+import { post } from '@/service/base'
import { FlowType } from '@/types/common'
import useOneStepRun from '../use-one-step-run'
@@ -180,14 +184,14 @@ vi.mock('@/app/components/workflow/nodes/variable-assigner/default', () => ({
default: {},
}))
-const renderUseOneStepRun = () =>
+const renderUseOneStepRun = (type: BlockEnum = BlockEnum.IfElse) =>
renderHook(() =>
useOneStepRun({
id: 'if-else-node',
flowId: 'app-id',
flowType: FlowType.appFlow,
data: {
- type: BlockEnum.IfElse,
+ type,
title: 'IF/ELSE',
desc: '',
},
@@ -239,4 +243,24 @@ describe('useOneStepRun single-run input vars', () => {
},
])
})
+
+ it('preserves the plugin request error and metadata when reporting a failed run', async () => {
+ const error = new ORPCError('forbidden', {
+ status: 403,
+ message: 'Plugin access denied',
+ data: { reason: 'PLUGIN_ACCESS_DENIED' },
+ cause: { headers: new Headers({ 'X-Request-Id': 'plugin-run-1' }) },
+ })
+ vi.mocked(post).mockRejectedValueOnce(error)
+ const reportError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { result } = renderUseOneStepRun(BlockEnum.TriggerPlugin)
+
+ await act(async () => {
+ expect(await result.current.handleRun({})).toBe(false)
+ })
+
+ expect(toast.error).toHaveBeenCalledWith('Plugin access denied')
+ expect(reportError).toHaveBeenCalledWith(error)
+ expect(reportError.mock.calls[0]?.[0]).toBe(error)
+ })
})
diff --git a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
index ddee45df591..77443dc0542 100644
--- a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
+++ b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
@@ -103,11 +103,6 @@ const checkValidFns: Partial<Record<BlockEnum, Function>> = {
[BlockEnum.HumanInput]: checkHumanInputValid,
}
-type RequestError = {
- message: string
- status: string
-}
-
export type Params<T> = {
id: string
flowId: string
@@ -579,18 +574,13 @@ const useOneStepRun = <T>({
const controller = new AbortController()
pluginSingleRunAbortRef.current = controller
- let requestError: RequestError | undefined
+ let requestError: unknown
const response: any = await post(urlPath, {
body: JSON.stringify({}),
signal: controller.signal,
})
- .catch(async (error: Response) => {
- const data = (await error.clone().json()) as Record<string, any>
- const { error: respError, status } = data || {}
- requestError = {
- message: respError,
- status,
- }
+ .catch((error: unknown) => {
+ requestError = error
return null
})
.finally(() => {
@@ -603,7 +593,7 @@ const useOneStepRun = <T>({
if (requestError) {
if (controller.signal.aborted) return null
- toast.error(requestError.message)
+ toast.error(requestError instanceof Error ? requestError.message : 'Unknown error')
cancelPluginSingleRun()
throw requestError
}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
index 40bf6462d4b..2bc015c0ee3 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -8,6 +8,7 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
import { AgentScope } from '@/features/agent-v2/analytics'
+import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { AppModeEnum } from '@/types/app'
import { FlowType } from '@/types/common'
@@ -497,7 +498,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
useAppStore.getState().setAppDetail({ mode: AppModeEnum.WORKFLOW } as never)
mocks.completeBuildConversation = undefined
permission.canCreateAgents = true
- mocks.loadBuildDraft.mockRejectedValue(new Response(null, { status: 404 }))
+ mocks.loadBuildDraft.mockRejectedValue(createHttpError(new Response(null, { status: 404 })))
mocks.checkoutBuildDraft.mockResolvedValue({
agent_soul: {},
draft: {
@@ -1049,7 +1050,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
it('should enter build draft mode without resetting the current inline build chat', async () => {
mocks.loadBuildDraft
- .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 404 })))
.mockResolvedValue({
agent_soul: {
schema_version: 1,
@@ -1202,7 +1203,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
it('should re-enable inline build draft actions when build chat fails', async () => {
mocks.loadBuildDraft
- .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 404 })))
.mockResolvedValue({
agent_soul: {
schema_version: 1,
@@ -1280,7 +1281,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {
it('should refresh the inline build debug conversation when restarting after a build send', async () => {
mocks.loadBuildDraft
- .mockRejectedValueOnce(new Response(null, { status: 404 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 404 })))
.mockResolvedValue({
agent_soul: {
schema_version: 1,
diff --git a/web/app/components/workflow/plugin-dependency/__tests__/hooks.spec.tsx b/web/app/components/workflow/plugin-dependency/__tests__/hooks.spec.tsx
index f4f2068f0c0..4624e967ab3 100644
--- a/web/app/components/workflow/plugin-dependency/__tests__/hooks.spec.tsx
+++ b/web/app/components/workflow/plugin-dependency/__tests__/hooks.spec.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import { usePluginDependencies } from '../hooks'
import { useStore } from '../store'
@@ -67,7 +68,9 @@ describe('usePluginDependencies', () => {
it.each([
[new TypeError('Network unavailable'), 'Network unavailable'],
[
- Response.json({ message: 'Dependency check unavailable' }, { status: 503 }),
+ createHttpError(new Response(null, { status: 503 }), {
+ message: 'Dependency check unavailable',
+ }),
'Dependency check unavailable',
],
])(
diff --git a/web/app/components/workflow/plugin-dependency/hooks.ts b/web/app/components/workflow/plugin-dependency/hooks.ts
index 285ddadb92d..3180798601c 100644
--- a/web/app/components/workflow/plugin-dependency/hooks.ts
+++ b/web/app/components/workflow/plugin-dependency/hooks.ts
@@ -1,10 +1,10 @@
import { useMutation } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { useCheckPipelineDependencies } from '@/service/use-pipeline'
+import { getErrorMessage } from '@/utils/error-message'
import { useStore as usePluginDependenciesStore } from './store'
export const usePluginDependencies = () => {
@@ -40,7 +40,7 @@ export const usePluginDependencies = () => {
toast.error(
t(($) => $.error, { ns: 'common' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
return false
diff --git a/web/app/components/workflow/run/__tests__/index.spec.tsx b/web/app/components/workflow/run/__tests__/index.spec.tsx
index cf9aaa96ff2..52a51868522 100644
--- a/web/app/components/workflow/run/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/run/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import type { WorkflowRunDetailResponse } from '@/models/log'
import type { NodeTracing, NodeTracingListResponse } from '@/types/workflow'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
import { BlockEnum, NodeRunningStatus } from '../../types'
import RunPanel from '../index'
@@ -211,8 +212,12 @@ describe('RunPanel', () => {
})
it('reports run-detail and tracing failures through toast.error', async () => {
- mockFetchRunDetail.mockRejectedValueOnce(new Error('detail boom'))
- mockFetchTracingList.mockRejectedValueOnce(new Error('tracing boom'))
+ mockFetchRunDetail.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 500 }), { message: 'detail boom' }),
+ )
+ mockFetchTracingList.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 500 }), { message: 'tracing boom' }),
+ )
renderWorkflowComponent(
<RunPanel
@@ -222,8 +227,8 @@ describe('RunPanel', () => {
)
await waitFor(() => {
- expect(mockToastError).toHaveBeenCalledWith('Error: detail boom')
- expect(mockToastError).toHaveBeenCalledWith('Error: tracing boom')
+ expect(mockToastError).toHaveBeenCalledWith('detail boom')
+ expect(mockToastError).toHaveBeenCalledWith('tracing boom')
})
})
diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsx
index 77870e8cb64..0ce931ee3f5 100644
--- a/web/app/components/workflow/run/index.tsx
+++ b/web/app/components/workflow/run/index.tsx
@@ -97,7 +97,8 @@ function RunSession({
setRunDetail(res)
if (getResultCallback) getResultCallback(res)
} catch (err) {
- if (lifetime.active && request === lifetime.detailRequest) toast.error(`${err}`)
+ if (lifetime.active && request === lifetime.detailRequest)
+ toast.error(err instanceof Error ? err.message : String(err))
} finally {
if (lifetime.active && request === lifetime.detailRequest) {
lifetime.detailSettled = true
@@ -117,7 +118,8 @@ function RunSession({
})
if (lifetime.active && request === lifetime.tracingRequest) setList(nodeList)
} catch (err) {
- if (lifetime.active && request === lifetime.tracingRequest) toast.error(`${err}`)
+ if (lifetime.active && request === lifetime.tracingRequest)
+ toast.error(err instanceof Error ? err.message : String(err))
} finally {
if (lifetime.active && request === lifetime.tracingRequest) {
lifetime.tracingSettled = true
diff --git a/web/app/components/workflow/update-dsl-modal.tsx b/web/app/components/workflow/update-dsl-modal.tsx
index e659fe181ed..864c8e94bf6 100644
--- a/web/app/components/workflow/update-dsl-modal.tsx
+++ b/web/app/components/workflow/update-dsl-modal.tsx
@@ -10,13 +10,13 @@ import { memo, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import DSLImportWarningDescription from '@/app/components/app/create-from-dsl-modal/dsl-import-warning-description'
import { Uploader } from '@/app/components/app/create-from-dsl-modal/uploader'
-import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
import { toast } from '@/app/notifications'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
import { consoleQuery } from '@/service/console'
import { fetchWorkflowDraft } from '@/service/workflow'
+import { getErrorMessage } from '@/utils/error-message'
import { collaborationManager } from './collaboration/core/collaboration-manager'
import { WORKFLOW_DATA_UPDATE } from './constants'
import {
@@ -96,7 +96,7 @@ const UpdateDSLModal = ({ appId, appMode, onCancel, onBackup, onImport }: Update
toast.error(
t(($) => $.error, { ns: 'common' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
// Reload the committed graph before the old canvas can resume autosaving.
@@ -129,7 +129,7 @@ const UpdateDSLModal = ({ appId, appMode, onCancel, onBackup, onImport }: Update
toast.error(
t(($) => $['common.importFailure'], { ns: 'workflow' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
}
diff --git a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
index e4f8499fff0..f73be396cd8 100644
--- a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
+++ b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
@@ -1,5 +1,6 @@
import type { GeneratedGraph } from '../types'
import { BlockEnum } from '@/app/components/workflow/types'
+import { createHttpError } from '@/service/http-error'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { AppModeEnum } from '@/types/app'
import {
@@ -342,7 +343,7 @@ describe('applyToCurrentApp', () => {
// A 409 from syncWorkflowDraft is the backend's signal that another tab
// edited the draft between our fetch and sync. The apply layer translates
- // that Response into a typed error so the caller can show a Reload
+ // that HTTP error into a domain error so the caller can show a Reload
// affordance instead of a generic "apply failed" toast.
it('should translate a 409 sync rejection into WorkflowApplyHashCollisionError', async () => {
mockFetchWorkflowDraft.mockResolvedValue({
@@ -351,9 +352,9 @@ describe('applyToCurrentApp', () => {
environment_variables: [],
conversation_variables: [],
})
- // ``base.ts`` rejects with the raw Response on non-401 — fake just the
- // ``status`` field, which is what ``isHashCollisionResponse`` consults.
- mockSyncWorkflowDraft.mockRejectedValueOnce({ status: 409, code: 'draft_workflow_not_sync' })
+ mockSyncWorkflowDraft.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 409 }), { code: 'draft_workflow_not_sync' }),
+ )
await expect(applyToCurrentApp({ appId: 'app-9', graph: makeGraph() })).rejects.toBeInstanceOf(
WorkflowApplyHashCollisionError,
@@ -370,13 +371,15 @@ describe('applyToCurrentApp', () => {
environment_variables: [],
conversation_variables: [],
})
- const original = { status: 500, code: 'internal_server_error' }
+ const original = createHttpError(new Response(null, { status: 500 }), {
+ code: 'internal_server_error',
+ })
mockSyncWorkflowDraft.mockRejectedValueOnce(original)
await expect(applyToCurrentApp({ appId: 'app-9', graph: makeGraph() })).rejects.toBe(original)
})
- it('should NOT translate string or null sync rejections', async () => {
+ it('should preserve network failures without treating them as hash collisions', async () => {
mockFetchWorkflowDraft.mockResolvedValue({
hash: 'h1',
features: {},
@@ -384,13 +387,8 @@ describe('applyToCurrentApp', () => {
conversation_variables: [],
})
- // String error
- const strError = 'some string error'
- mockSyncWorkflowDraft.mockRejectedValueOnce(strError)
- await expect(applyToCurrentApp({ appId: 'app-9', graph: makeGraph() })).rejects.toBe(strError)
-
- // Null error
- mockSyncWorkflowDraft.mockRejectedValueOnce(null)
- await expect(applyToCurrentApp({ appId: 'app-9', graph: makeGraph() })).rejects.toBeNull()
+ const error = new TypeError('Failed to fetch')
+ mockSyncWorkflowDraft.mockRejectedValueOnce(error)
+ await expect(applyToCurrentApp({ appId: 'app-9', graph: makeGraph() })).rejects.toBe(error)
})
})
diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.ts
index 3b2059aa8b3..0437a7f604b 100644
--- a/web/app/components/workflow/workflow-generator/apply.ts
+++ b/web/app/components/workflow/workflow-generator/apply.ts
@@ -2,6 +2,7 @@ import type { GeneratedGraph, WorkflowGeneratorMode } from './types'
import type { AppModeEnum } from '@/types/app'
import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'
import { consoleClient } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'
const MODE_TO_APP_MODE = {
@@ -46,14 +47,6 @@ export class WorkflowApplyOrphanError extends Error {
}
}
-const isHashCollisionResponse = (e: unknown): boolean => {
- // The shared ``post()`` wrapper rejects with the raw ``Response`` for non-401
- // failures (see ``service/base.ts::request`` catch branch). At this layer the
- // only reliable signal is the HTTP status.
- if (!e || typeof e !== 'object') return false
- return (e as { status?: number }).status === 409
-}
-
// Derive a sane App name from the user's instruction: trim, cap at 40 chars,
// strip trailing punctuation.
const deriveAppName = (instruction: string): string => {
@@ -190,9 +183,9 @@ export const applyToCurrentApp = async ({
})
} catch (e) {
// 409 → draft was edited in another tab between our fetch and sync.
- // Translate the raw Response rejection into a typed error so the caller
+ // Translate the HTTP error into a domain error so the caller
// can show a Reload affordance instead of a generic "apply failed" toast.
- if (isHashCollisionResponse(e)) throw new WorkflowApplyHashCollisionError()
+ if (getHttpErrorStatus(e) === 409) throw new WorkflowApplyHashCollisionError()
throw e
}
}
diff --git a/web/app/education/verify/__tests__/verify-flow.spec.tsx b/web/app/education/verify/__tests__/verify-flow.spec.tsx
index e206ba292e2..1ac137115c7 100644
--- a/web/app/education/verify/__tests__/verify-flow.spec.tsx
+++ b/web/app/education/verify/__tests__/verify-flow.spec.tsx
@@ -1,5 +1,6 @@
import { screen, waitFor } from '@testing-library/react'
import { StrictMode } from 'react'
+import { createHttpError } from '@/service/http-error'
import { createConsoleQueryWrapper, seedFeatures } from '@/test/console/query-data'
import { render } from '@/test/console/render'
import { EducationVerifyFlow } from '../verify-flow'
@@ -92,7 +93,7 @@ describe('EducationVerifyFlow', () => {
})
it('renders the generic error state when verification fails', async () => {
- mockRequestVerification.mockRejectedValue(new Response(null, { status: 503 }))
+ mockRequestVerification.mockRejectedValue(createHttpError(new Response(null, { status: 503 })))
renderFlow({})
diff --git a/web/app/error.tsx b/web/app/error.tsx
index fb6c10a076e..2f77ea183d2 100644
--- a/web/app/error.tsx
+++ b/web/app/error.tsx
@@ -4,7 +4,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { useQueryErrorResetBoundary } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { FullScreenLoading } from '@/app/components/full-screen-loading'
-import { isLegacyBase401 } from '@/features/account-profile/client'
+import { isUnauthorizedError } from '@/service/http-error'
type Props = Readonly<{
error: Error & { digest?: string }
@@ -17,7 +17,7 @@ export default function AppError({ error, retry }: Props) {
console.error(error)
- if (isLegacyBase401(error)) return <FullScreenLoading />
+ if (isUnauthorizedError(error)) return <FullScreenLoading />
return (
<div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-background-body">
diff --git a/web/app/signin/__tests__/normal-form.spec.tsx b/web/app/signin/__tests__/normal-form.spec.tsx
index 30819cc8566..4e6f9cb3ff7 100644
--- a/web/app/signin/__tests__/normal-form.spec.tsx
+++ b/web/app/signin/__tests__/normal-form.spec.tsx
@@ -16,7 +16,6 @@ vi.mock('@tanstack/react-query', async () => {
})
vi.mock('@/features/account-profile/client', () => ({
- isLegacyBase401: vi.fn(() => false),
userProfileQueryOptions: vi.fn(() => ({
queryKey: ['account', 'profile'],
queryFn: vi.fn(),
diff --git a/web/app/signin/check-code/__tests__/page.spec.tsx b/web/app/signin/check-code/__tests__/page.spec.tsx
index 36225dae6c9..39a42b8c959 100644
--- a/web/app/signin/check-code/__tests__/page.spec.tsx
+++ b/web/app/signin/check-code/__tests__/page.spec.tsx
@@ -5,6 +5,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { emailLoginWithCode, sendEMailLoginCode } from '@/service/common'
+import { createHttpError } from '@/service/http-error'
import { seedSystemFeatures } from '@/test/console/query-data'
import CheckCode from '../page'
@@ -533,7 +534,7 @@ describe('CheckCode', () => {
resolveProfileResponse = resolve
})
serviceBaseMocks.get
- .mockRejectedValueOnce(new Response(null, { status: 401 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 401 })))
.mockReturnValueOnce(profileResponse)
await queryClient.query(profileQueryOptions).catch(noop)
expect(queryClient.getQueryState(profileQueryKey)?.status).toBe('error')
diff --git a/web/app/signin/components/sso-auth.tsx b/web/app/signin/components/sso-auth.tsx
index 2f035ff88b6..c7677388d8e 100644
--- a/web/app/signin/components/sso-auth.tsx
+++ b/web/app/signin/components/sso-auth.tsx
@@ -1,8 +1,10 @@
'use client'
+
import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
import type { FC } from 'react'
import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
+import { ORPCError } from '@orpc/client'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
@@ -14,16 +16,11 @@ type SSOAuthProps = {
}
// The request layer already toasts HTTP errors whose JSON body carries a message.
-const hasNotifiedRequestError = async (error: unknown) => {
- if (!(error instanceof Response) || error.status === 401) return false
- try {
- const body: unknown = await error.clone().json()
- if (!body || typeof body !== 'object') return false
- return ('message' in body && !!body.message) || ('error' in body && !!body.error)
- } catch {
- return false
- }
-}
+const hasNotifiedRequestError = (error: unknown) =>
+ error instanceof ORPCError &&
+ error.status !== 401 &&
+ ((typeof error.data?.message === 'string' && !!error.data.message) ||
+ (typeof error.data?.error === 'string' && !!error.data.error))
const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
const router = useRouter()
@@ -33,8 +30,8 @@ const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
const [isLoading, setIsLoading] = useState(false)
- const handleSSOError = async (error: unknown) => {
- if (await hasNotifiedRequestError(error)) return
+ const handleSSOError = (error: unknown) => {
+ if (hasNotifiedRequestError(error)) return
toast.error(t(($) => $['error.ssoFailed'], { ns: 'login' }))
}
diff --git a/web/app/signin/invite-settings/page.tsx b/web/app/signin/invite-settings/page.tsx
index ade6672bc2c..28824070506 100644
--- a/web/app/signin/invite-settings/page.tsx
+++ b/web/app/signin/invite-settings/page.tsx
@@ -20,7 +20,7 @@ import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { LICENSE_LINK } from '@/constants/link'
-import { isLegacyBase401, userProfileQueryOptions } from '@/features/account-profile/client'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useDocumentTitle from '@/hooks/use-document-title'
import { i18n } from '@/i18n'
@@ -30,6 +30,7 @@ import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { activateMember } from '@/service/common'
import { consoleQuery } from '@/service/console'
+import { isUnauthorizedError } from '@/service/http-error'
import { useInvitationCheck } from '@/service/use-common'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { getBrowserTimezone, timezones } from '@/utils/timezone'
@@ -78,7 +79,7 @@ export default function InviteSettingsPage() {
error: profileError,
} = useQuery({
...userProfileQueryOptions(),
- throwOnError: (err) => !isLegacyBase401(err),
+ throwOnError: (err) => !isUnauthorizedError(err),
refetchOnWindowFocus: false,
})
const locale = useLocale()
@@ -114,7 +115,7 @@ export default function InviteSettingsPage() {
!isProfilePending &&
Boolean(
checkRes?.is_valid &&
- (isLegacyBase401(profileError) || (userResp && !isInvitationForCurrentAccount)),
+ (isUnauthorizedError(profileError) || (userResp && !isInvitationForCurrentAccount)),
)
const requiresAccountSetup =
checkRes?.data?.requires_setup ?? checkRes?.data?.account_status === 'pending'
diff --git a/web/app/signin/normal-form.tsx b/web/app/signin/normal-form.tsx
index bc8ad3ed1bf..ec95dab3b73 100644
--- a/web/app/signin/normal-form.tsx
+++ b/web/app/signin/normal-form.tsx
@@ -6,11 +6,12 @@ import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toast } from '@/app/notifications'
-import { isLegacyBase401, userProfileQueryOptions } from '@/features/account-profile/client'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { invitationCheck } from '@/service/common'
+import { isUnauthorizedError } from '@/service/http-error'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { basePath } from '@/utils/var'
import MailAndCodeAuth from './components/mail-and-code-auth'
@@ -38,7 +39,7 @@ function NormalForm() {
error: probeError,
} = useQuery({
...userProfileQueryOptions(),
- throwOnError: (err) => !isLegacyBase401(err),
+ throwOnError: (err) => !isUnauthorizedError(err),
refetchOnWindowFocus: false,
})
const isLoggedIn = !!userResp && !probeError
diff --git a/web/app/signin/one-more-step.tsx b/web/app/signin/one-more-step.tsx
index f529e8483fd..d8ad7297c0e 100644
--- a/web/app/signin/one-more-step.tsx
+++ b/web/app/signin/one-more-step.tsx
@@ -1,4 +1,5 @@
'use client'
+
import type { Reducer } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
@@ -24,6 +25,7 @@ import { languages } from '@/i18n/language'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { useOneMoreStep } from '@/service/use-common'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { timezones } from '@/utils/timezone'
@@ -64,15 +66,6 @@ const TIMEZONE_OPTIONS: SelectOption[] = timezones.map((item) => ({
name: item.name,
}))
-const hasStatus = (error: unknown): error is { status: number } => {
- return (
- typeof error === 'object' &&
- error !== null &&
- 'status' in error &&
- typeof error.status === 'number'
- )
-}
-
const OneMoreStep = () => {
const { t } = useTranslation(['common', 'login'])
const router = useRouter()
@@ -109,7 +102,7 @@ const OneMoreStep = () => {
await queryClient.resetQueries({ queryKey: consoleQuery.account.profile.get.key() })
replaceLoginRedirect(resolvePostLoginRedirect(searchParams), router.replace, basePath)
} catch (error: unknown) {
- if (hasStatus(error) && error.status === 400)
+ if (getHttpErrorStatus(error) === 400)
toast.error(t(($) => $.invalidInvitationCode, { ns: 'login' }))
}
}
diff --git a/web/features/account-profile/client.ts b/web/features/account-profile/client.ts
index cfddc3df418..5fa181b562e 100644
--- a/web/features/account-profile/client.ts
+++ b/web/features/account-profile/client.ts
@@ -4,6 +4,7 @@ import { IS_DEV } from '@/config'
// oxlint-disable-next-line no-restricted-imports
import { get } from '@/service/base'
import { consoleQuery } from '@/service/console'
+import { isUnauthorizedError } from '@/service/http-error'
export type UserProfileWithMeta = {
profile: GetAccountProfileResponse
@@ -13,9 +14,6 @@ export type UserProfileWithMeta = {
}
}
-export const isLegacyBase401 = (err: unknown): boolean =>
- err instanceof Response && err.status === 401
-
export const userProfileQueryOptions = () =>
queryOptions<UserProfileWithMeta>({
queryKey: consoleQuery.account.profile.get.queryKey(),
@@ -37,5 +35,5 @@ export const userProfileQueryOptions = () =>
},
}
},
- retry: (failureCount, error) => !isLegacyBase401(error) && failureCount < 3,
+ retry: (failureCount, error) => !isUnauthorizedError(error) && failureCount < 3,
})
diff --git a/web/features/account-profile/server.ts b/web/features/account-profile/server.ts
index 1c132254603..8ffac2a49a1 100644
--- a/web/features/account-profile/server.ts
+++ b/web/features/account-profile/server.ts
@@ -6,6 +6,7 @@ import {
getServerConsoleRequestHeaders,
resolveServerConsoleApiUrl,
} from '@/service/console/server'
+import { httpErrorFromResponse } from '@/service/http-error'
const ACCOUNT_PROFILE_PATH = '/account/profile'
@@ -22,7 +23,7 @@ export const serverUserProfileQueryOptions = () =>
cache: 'no-store',
})
- if (!response.ok) throw response
+ if (!response.ok) throw await httpErrorFromResponse(response)
const profile: GetAccountProfileResponse = await response.clone().json()
return {
diff --git a/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx b/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
index b6164182b8b..6c3b86f0446 100644
--- a/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
+++ b/web/features/agent-v2/agent-detail/__tests__/layout.spec.tsx
@@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'
import { AgentPermission } from '@/features/agent-v2/acl'
import useDocumentTitle from '@/hooks/use-document-title'
import { consoleQuery } from '@/service/console'
+import { createHttpError } from '@/service/http-error'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { createAgentFixture } from '@/test/fixtures/agent'
import { AgentDetailLayout } from '../layout'
@@ -111,7 +112,7 @@ describe('AgentDetailLayout', () => {
.find({ queryKey: detailKey })!
.setState({
data: undefined,
- error: Object.assign(new Response(null, { status: 404 }), {
+ error: Object.assign(createHttpError(new Response(null, { status: 404 })), {
name: 'NotFound',
message: 'Not found',
}),
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
index c6bab1d0786..29b5a741262 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
@@ -7,6 +7,7 @@ import { useState } from 'react'
import { AgentPermission } from '@/features/agent-v2/acl'
import { AgentScope } from '@/features/agent-v2/analytics'
import { consoleQuery } from '@/service/console'
+import { createHttpError } from '@/service/http-error'
import { renderWithNuqs as render } from '@/test/nuqs-testing'
import { AgentConfigureComposerScope } from '../components/composer-session'
import { useAgentConfigureData } from '../hooks'
@@ -1913,7 +1914,7 @@ describe('AgentConfigurePage', () => {
mocks.queryState.buildDraft = {
data: undefined as unknown,
dataUpdatedAt: 0,
- error: new Response(null, { status: 404 }),
+ error: createHttpError(new Response(null, { status: 404 })),
isFetching: false,
isError: true,
isPending: false,
@@ -2287,7 +2288,7 @@ describe('AgentConfigurePage', () => {
mocks.queryState.buildDraft = {
data: undefined as unknown,
dataUpdatedAt: 0,
- error: new Response(null, { status: 404 }),
+ error: createHttpError(new Response(null, { status: 404 })),
isFetching: false,
isError: true,
isPending: false,
@@ -2359,7 +2360,7 @@ describe('AgentConfigurePage', () => {
mocks.queryState.buildDraft = {
data: undefined as unknown,
dataUpdatedAt: 0,
- error: new Response(null, { status: 404 }),
+ error: createHttpError(new Response(null, { status: 404 })),
isFetching: false,
isError: true,
isPending: false,
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
index 08040d8c76b..b2dfbd4d294 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
@@ -1,6 +1,7 @@
import type { PropsWithChildren } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import { useAgentConfigureBuildDraftData } from '../use-agent-configure-build-draft'
const mocks = vi.hoisted(() => ({
@@ -71,7 +72,7 @@ describe('build draft refresh errors', () => {
const { result, setSoulSourceOverride } = setup()
await waitFor(() => expect(result.current.isActive).toBe(true))
- const notFound = new Response(null, { status: 404 })
+ const notFound = createHttpError(new Response(null, { status: 404 }))
mocks.request.mockRejectedValueOnce(notFound)
await act(async () => {
const refreshed = await result.current.refetch()
@@ -88,7 +89,7 @@ describe('build draft refresh errors', () => {
const { result, setSoulSourceOverride } = setup()
await waitFor(() => expect(result.current.isActive).toBe(true))
- const serverError = new Response(null, { status: 500 })
+ const serverError = createHttpError(new Response(null, { status: 500 }))
mocks.request.mockRejectedValueOnce(serverError)
await act(async () => {
const refreshed = await result.current.refetch()
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
index 2428d8857de..2c153d9b912 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
@@ -18,6 +18,7 @@ import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
import { consoleQuery } from '@/service/console'
+import { httpErrorFromResponse } from '@/service/http-error'
import { createAgentFixture } from '@/test/fixtures/agent'
import { useAgentConfigureSync } from '../use-agent-configure-sync'
@@ -1397,12 +1398,13 @@ describe('useAgentConfigureSync', () => {
statusText: 'Bad Request',
},
)
- publishAgentMutationFn.mockRejectedValueOnce(responseError)
+ const apiError = await httpErrorFromResponse(responseError)
+ publishAgentMutationFn.mockRejectedValueOnce(apiError)
const { result } = renderUseAgentConfigureSync({
currentModel: configuredModel,
})
- await expect(result.current.publishDraft()).rejects.toBe(responseError)
+ await expect(result.current.publishDraft()).rejects.toBe(apiError)
expect(toastMock.error).toHaveBeenCalledWith('Model credential validation failed')
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
index f92e3707bdb..b00c970d2da 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
@@ -12,6 +12,7 @@ import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/c
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
+import { createHttpError } from '@/service/http-error'
import { seedFeatures } from '@/test/console/query-data'
import { AgentOrchestrateAddActionsProvider } from '../../add-actions'
import { useAgentOrchestrateAddActions } from '../../add-actions-context'
@@ -907,9 +908,9 @@ describe('AgentSkills', () => {
it('explains when an agent has reached the library skill limit', async () => {
const user = userEvent.setup()
- mocks.replaceAgentSkillBindingsMutationFn.mockRejectedValueOnce({
- code: 'too_many_agent_skills',
- })
+ mocks.replaceAgentSkillBindingsMutationFn.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), { code: 'too_many_agent_skills' }),
+ )
mocks.workspaceSkillsInfiniteOptions.mockImplementation((options) => {
const { input, getNextPageParam, initialPageParam } = options as {
input: (pageParam: number) => { query?: { limit?: number } }
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
index 4f551cc7b0a..212a11131ee 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
@@ -37,11 +37,7 @@ import {
removeAgentSkillAtom,
upsertAgentSkillAtom,
} from '@/features/agent-v2/agent-composer/store-modules/skills'
-import {
- getSkillErrorCode,
- getSkillErrorDetailString,
- normalizeSkillError,
-} from '@/features/skills/error'
+import { getSkillErrorCode, getSkillErrorDetailString } from '@/features/skills/error'
import { TagFilter } from '@/features/tag-management/components/tag-filter'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
@@ -525,9 +521,8 @@ export function AgentSkills() {
},
},
{
- onError: async (error) => {
- const normalizedError = await normalizeSkillError(error)
- const errorCode = getSkillErrorCode(normalizedError)
+ onError: (error) => {
+ const errorCode = getSkillErrorCode(error)
if (errorCode === 'too_many_agent_skills') {
toast.error(
t(($) => $['agentDetail.configure.skills.workspaceSelector.limitReached']),
@@ -537,7 +532,7 @@ export function AgentSkills() {
if (errorCode === 'skill_name_conflict') {
toast.error(
tSkill(($) => $['skillManagement.errors.nameConflict'], {
- name: getSkillErrorDetailString(normalizedError, 'name') ?? '',
+ name: getSkillErrorDetailString(error, 'name') ?? '',
}),
)
return
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
index 6d8df0af5ca..15c7baefb48 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
@@ -14,12 +14,14 @@ import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-stat
import { Dialog } from '@langgenius/dify-ui/dialog'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Tabs, TabsIndicator, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
+import { ORPCError } from '@orpc/client'
import { skipToken, useMutation, useQueries, useQuery } from '@tanstack/react-query'
import { useCallback, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { getFileIconType } from '@/features/agent-v2/file-icon'
import { consoleClient, consoleQuery } from '@/service/console'
+import { isNotFoundError } from '@/service/http-error'
import { downloadUrl } from '@/utils/download'
import { AgentSkillDetailDialog } from '../orchestrate/skills/detail-dialog'
import {
@@ -49,10 +51,6 @@ export type AgentWorkingDirectorySource =
workflowRunId: string
}
-type SandboxErrorPayload = {
- code?: string
-}
-
const getSandboxRootPath = (path: string): AgentWorkingDirectoryRootPath =>
path === AGENT_SAVED_FILES_ROOT_PATH || path.startsWith(`${AGENT_SAVED_FILES_ROOT_PATH}/`)
? AGENT_SAVED_FILES_ROOT_PATH
@@ -226,19 +224,12 @@ function countReadableFiles(files: AgentFileNode[]): number {
}, 0)
}
-async function isNoActiveBindingError(error: unknown) {
- if (!(error instanceof Response) || error.status !== 404) return false
+function isNoActiveBindingError(error: unknown) {
+ if (!(error instanceof ORPCError) || error.status !== 404) return false
- try {
- const payload = (await error.clone().json()) as SandboxErrorPayload
- return payload.code === 'no_active_binding'
- } catch {
- return false
- }
+ return error.code === 'no_active_binding'
}
-const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
-
export function AgentWorkingDirectoryPanel({
source,
onOpenChange,
@@ -315,7 +306,7 @@ export function AgentWorkingDirectoryPanel({
try {
return await fileListQueryOptions.queryFn(context)
} catch (error) {
- if (await isNoActiveBindingError(error)) {
+ if (isNoActiveBindingError(error)) {
return {
entries: [],
path: '.',
@@ -337,7 +328,7 @@ export function AgentWorkingDirectoryPanel({
try {
return await queryOptions.queryFn(context)
} catch (error) {
- if (await isNoActiveBindingError(error)) {
+ if (isNoActiveBindingError(error)) {
return {
entries: [],
path,
@@ -418,7 +409,7 @@ export function AgentWorkingDirectoryPanel({
try {
return await fileReadQueryOptions.queryFn(context)
} catch (error) {
- if (isNotFoundResponse(error)) {
+ if (isNotFoundError(error)) {
return {
binary: false,
path: selectedWorkingDirectoryFile?.id ?? '',
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
index e8090f3049f..1c86b9db5c3 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
@@ -18,9 +18,9 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
import { consoleQuery } from '@/service/console'
+import { isNotFoundError } from '@/service/http-error'
import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'
-const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
const BUILD_NOTE_FILE_ID = '__agent_config_build_note__'
const BUILD_NOTE_FILE_NAME = 'build_note.md'
@@ -182,7 +182,7 @@ export function useAgentConfigureBuildDraftData({
try {
return await buildDraftQueryOptions.queryFn(context)
} catch (error) {
- if (isNotFoundResponse(error)) setSoulSourceOverride('draft')
+ if (isNotFoundError(error)) setSoulSourceOverride('draft')
else toast.error(t(($) => $['api.actionFailed']))
throw error
}
@@ -200,7 +200,7 @@ export function useAgentConfigureBuildDraftData({
isPending: isBuildDraftPending,
refetch: refetchBuildDraft,
} = buildDraftQuery
- const buildDraftNotFound = isNotFoundResponse(buildDraftError)
+ const buildDraftNotFound = isNotFoundError(buildDraftError)
const resolvedSoulSource: AgentConfigureSoulSource = isViewingVersion
? 'view-version'
: (soulSourceOverride ??
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
index b2fccfa44bf..bae68ce6770 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
@@ -478,20 +478,7 @@ export function useAgentConfigureSync({
})
return { kind: published.publication_kind, draft }
} catch (error) {
- let errorData: unknown = error
- if (error instanceof Response) {
- try {
- errorData = await error.clone().json()
- } catch {}
- }
- toast.error(
- errorData &&
- typeof errorData === 'object' &&
- 'message' in errorData &&
- typeof errorData.message === 'string'
- ? errorData.message
- : tCommon(($) => $['api.actionFailed']),
- )
+ toast.error(error instanceof Error ? error.message : tCommon(($) => $['api.actionFailed']))
throw error
} finally {
publishInFlightRef.current = false
diff --git a/web/features/agent-v2/agent-detail/layout.tsx b/web/features/agent-v2/agent-detail/layout.tsx
index 8fefef8c432..0a09ccab707 100644
--- a/web/features/agent-v2/agent-detail/layout.tsx
+++ b/web/features/agent-v2/agent-detail/layout.tsx
@@ -9,21 +9,20 @@ import { getAgentDefaultSection, getAgentSectionAccess } from '@/features/agent-
import { useAgentPermissions } from '@/features/agent-v2/permissions'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePathname, useRouter } from '@/next/navigation'
+import { isNotFoundError } from '@/service/http-error'
type AgentDetailLayoutProps = {
agentId: string
children: ReactNode
}
-const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
-
export function AgentDetailLayout({ agentId, children }: AgentDetailLayoutProps) {
const { t } = useTranslation(['agentV2', 'agentRoster'])
const pathname = usePathname()
const router = useRouter()
const { t: tCommon } = useTranslation(['common'])
const { agentQuery, ...capabilities } = useAgentPermissions(agentId)
- const shouldRedirectToRoster = isNotFoundResponse(agentQuery.error)
+ const shouldRedirectToRoster = isNotFoundError(agentQuery.error)
const section = pathname.endsWith('/access-config')
? 'access-config'
: pathname.endsWith('/access')
diff --git a/web/features/new-rag/__tests__/auxiliary-task-read-guard.spec.ts b/web/features/new-rag/__tests__/auxiliary-task-read-guard.spec.ts
index fab74652567..c846caa9377 100644
--- a/web/features/new-rag/__tests__/auxiliary-task-read-guard.spec.ts
+++ b/web/features/new-rag/__tests__/auxiliary-task-read-guard.spec.ts
@@ -1,4 +1,5 @@
import { act, renderHook } from '@testing-library/react'
+import { createHttpError } from '@/service/http-error'
import {
createAuxiliaryTaskReadGuard,
useAuxiliaryTaskReadGuard,
@@ -75,7 +76,7 @@ describe('createAuxiliaryTaskReadGuard', () => {
it('clears local denial and version blocks after document permission returns', async () => {
const refetchDocuments = vi
.fn()
- .mockResolvedValue({ error: new Response(null, { status: 403 }) })
+ .mockResolvedValue({ error: createHttpError(new Response(null, { status: 403 })) })
const { result, rerender } = renderHook(
({ documentPermissionDenied }) =>
useAuxiliaryTaskReadGuard({ documentPermissionDenied, refetchDocuments }),
diff --git a/web/features/new-rag/__tests__/crawl-selection-form.spec.tsx b/web/features/new-rag/__tests__/crawl-selection-form.spec.tsx
index 7b2f412be40..4737213cec0 100644
--- a/web/features/new-rag/__tests__/crawl-selection-form.spec.tsx
+++ b/web/features/new-rag/__tests__/crawl-selection-form.spec.tsx
@@ -10,6 +10,7 @@ import userEvent from '@testing-library/user-event'
import { createInstance } from 'i18next'
import datasetTranslations from '@/i18n/locales/en-US/dataset.json'
import { getInitOptions } from '@/i18n/settings'
+import { createHttpError } from '@/service/http-error'
import { render } from '@/test/console/render'
import { CrawlSelectionForm } from '../crawl-selection-form'
@@ -563,7 +564,9 @@ describe('CrawlSelectionForm', () => {
}),
)
clientMock.updatePolicy
- .mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }))
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 409 }), { message: 'conflict' }),
+ )
.mockResolvedValueOnce(policy({ enabled: false, mode: 'manual', revision: 4 }))
const user = userEvent.setup()
renderSelectionForm()
@@ -611,7 +614,7 @@ describe('CrawlSelectionForm', () => {
it('creates the initial provider policy when a provisional source has no policy yet', async () => {
clientMock.getPolicy.mockRejectedValue(
- Object.assign(new Error('policy not found'), { status: 404 }),
+ createHttpError(new Response(null, { status: 404 }), { message: 'policy not found' }),
)
clientMock.updatePolicy.mockResolvedValue(policy({ mode: 'provider', revision: 1 }))
const user = userEvent.setup()
diff --git a/web/features/new-rag/__tests__/create-knowledge-page.spec.tsx b/web/features/new-rag/__tests__/create-knowledge-page.spec.tsx
index 5f093d67446..a0def68c628 100644
--- a/web/features/new-rag/__tests__/create-knowledge-page.spec.tsx
+++ b/web/features/new-rag/__tests__/create-knowledge-page.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { confirmPageLeave } from '@/utils/page-leave-guard'
import { CreateKnowledgePage } from '../create-knowledge-page'
import { newKnowledgeSourceDraftStorageKey } from '../routes'
@@ -280,7 +281,7 @@ describe('CreateKnowledgePage', () => {
vi.mocked(globalThis.crypto.randomUUID)
.mockReturnValueOnce('11111111-1111-4111-8111-111111111111')
.mockReturnValueOnce('22222222-2222-4222-8222-222222222222')
- serviceMock.create.mockRejectedValueOnce({ status })
+ serviceMock.create.mockRejectedValueOnce(createHttpError(new Response(null, { status })))
renderPage()
await fillRequiredFields(user)
@@ -309,7 +310,7 @@ describe('CreateKnowledgePage', () => {
'keeps request identity frozen after an ambiguous %s response',
async (status) => {
const user = userEvent.setup()
- serviceMock.create.mockRejectedValueOnce({ status })
+ serviceMock.create.mockRejectedValueOnce(createHttpError(new Response(null, { status })))
renderPage()
await fillRequiredFields(user)
diff --git a/web/features/new-rag/__tests__/document-detail-page.spec.tsx b/web/features/new-rag/__tests__/document-detail-page.spec.tsx
index 030d1d2605e..1300f480a12 100644
--- a/web/features/new-rag/__tests__/document-detail-page.spec.tsx
+++ b/web/features/new-rag/__tests__/document-detail-page.spec.tsx
@@ -8,6 +8,7 @@ import type {
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import copy from 'copy-to-clipboard'
+import { createHttpError } from '@/service/http-error'
import { renderWithNuqs as render } from '@/test/nuqs-testing'
import { DocumentDetailPage } from '../document-detail-page'
@@ -834,7 +835,7 @@ describe('DocumentDetailPage', () => {
it('distinguishes missing, restricted, and retryable document failures', async () => {
const user = userEvent.setup()
documentQuery.data = undefined
- documentQuery.error = { status: 404 }
+ documentQuery.error = createHttpError(new Response(null, { status: 404 }))
const rendered = render(
<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />,
)
@@ -934,7 +935,7 @@ describe('DocumentDetailPage', () => {
})
it('does not render cached document data after a refetch returns 403 or 404', () => {
- documentQuery.error = { status: 404 }
+ documentQuery.error = createHttpError(new Response(null, { status: 404 }))
const rendered = render(
<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />,
)
@@ -944,7 +945,7 @@ describe('DocumentDetailPage', () => {
).toBeInTheDocument()
expect(screen.queryByText('sso-enterprise.pdf')).toBeNull()
- documentQuery.error = { status: 403 }
+ documentQuery.error = createHttpError(new Response(null, { status: 403 }))
rendered.rerender(<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />)
expect(screen.queryByText('sso-enterprise.pdf')).toBeNull()
@@ -953,8 +954,8 @@ describe('DocumentDetailPage', () => {
retry: (failureCount: number, error: unknown) => boolean
}
).retry
- expect(retry(0, { status: 403 })).toBe(false)
- expect(retry(0, { status: 404 })).toBe(false)
+ expect(retry(0, createHttpError(new Response(null, { status: 403 })))).toBe(false)
+ expect(retry(0, createHttpError(new Response(null, { status: 404 })))).toBe(false)
expect(retry(0, new Error('temporary'))).toBe(true)
})
@@ -1048,11 +1049,15 @@ describe('DocumentDetailPage', () => {
).toBe(false)
expect(
discoveryOptions.refetchInterval({
- state: { data: { items: [] }, error: { status: 403 } },
+ state: { data: { items: [] }, error: createHttpError(new Response(null, { status: 403 })) },
}),
).toBe(false)
- expect(discoveryOptions.retry(0, { status: 403 })).toBe(false)
- expect(discoveryOptions.retry(0, { status: 404 })).toBe(false)
+ expect(discoveryOptions.retry(0, createHttpError(new Response(null, { status: 403 })))).toBe(
+ false,
+ )
+ expect(discoveryOptions.retry(0, createHttpError(new Response(null, { status: 404 })))).toBe(
+ false,
+ )
})
it('keeps submission protection while a delayed status recheck is unresolved', async () => {
@@ -1220,7 +1225,7 @@ describe('DocumentDetailPage', () => {
it('stops snapshot polling and distrusts stale active task data after 403 or 404', async () => {
tasksQuery.data = { pages: [{ items: [task({ state: 'running' })] }] }
- taskSnapshotQuery.error = { status: 404 }
+ taskSnapshotQuery.error = createHttpError(new Response(null, { status: 404 }))
const rendered = render(
<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />,
)
@@ -1231,11 +1236,15 @@ describe('DocumentDetailPage', () => {
state: { data?: DocumentProcessingTask; error?: unknown }
}) => number | false
}
- expect(snapshotOptions.refetchInterval({ state: { error: { status: 404 } } })).toBe(false)
+ expect(
+ snapshotOptions.refetchInterval({
+ state: { error: createHttpError(new Response(null, { status: 404 })) },
+ }),
+ ).toBe(false)
await waitFor(() => expect(queryClient.invalidateQueries).toHaveBeenCalled())
queryClient.invalidateQueries.mockClear()
- taskSnapshotQuery.error = { status: 403 }
+ taskSnapshotQuery.error = createHttpError(new Response(null, { status: 403 }))
rendered.rerender(<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />)
expect(screen.getByRole('alert')).toHaveTextContent(
'dataset.newKnowledge.tasksErrorDescription',
@@ -1247,7 +1256,7 @@ describe('DocumentDetailPage', () => {
it('clears both task caches when a submission-discovered task snapshot returns 404', async () => {
submissionTasksQuery.data = { items: [task({ state: 'running' })] }
- taskSnapshotQuery.error = { status: 404 }
+ taskSnapshotQuery.error = createHttpError(new Response(null, { status: 404 }))
const rendered = render(
<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />,
@@ -1297,7 +1306,9 @@ describe('DocumentDetailPage', () => {
finishPermissionRefresh = resolve
}),
)
- reindexMutation.mutateAsync.mockRejectedValueOnce({ status: 403 })
+ reindexMutation.mutateAsync.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 })),
+ )
render(<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />)
const button = screen.getByRole('button', { name: 'dataset.newKnowledge.reindexDocument' })
@@ -1318,7 +1329,9 @@ describe('DocumentDetailPage', () => {
data: { dataset: { default_permission_keys: ['dataset.acl.edit'] } },
error: new Error('permission refresh failed'),
})
- reindexMutation.mutateAsync.mockRejectedValueOnce({ status: 403 })
+ reindexMutation.mutateAsync.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 })),
+ )
render(<DocumentDetailPage documentId="document-1" knowledgeSpaceId="space-1" />)
const button = screen.getByRole('button', { name: 'dataset.newKnowledge.reindexDocument' })
diff --git a/web/features/new-rag/__tests__/documents-page.spec.tsx b/web/features/new-rag/__tests__/documents-page.spec.tsx
index e9ecb1e1284..ee8a815c174 100644
--- a/web/features/new-rag/__tests__/documents-page.spec.tsx
+++ b/web/features/new-rag/__tests__/documents-page.spec.tsx
@@ -3,9 +3,11 @@ import type {
LogicalDocument,
Source,
} from '@dify/contracts/knowledge-fs/types.gen'
+import { ORPCError } from '@orpc/client'
import { hashKey } from '@tanstack/react-query'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { renderWithNuqs as render } from '@/test/nuqs-testing'
import { DocumentsPage } from '../documents-page'
import { TaskEventObserver } from '../task-event-observer'
@@ -884,7 +886,7 @@ describe('DocumentsPage', () => {
it('distinguishes a permission failure and exposes retry for other load errors', async () => {
const user = userEvent.setup()
documentsQuery.data = undefined
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
const { rerender } = render(<DocumentsPage knowledgeSpaceId="space-1" />)
expect(screen.getByRole('alert')).toHaveTextContent(
@@ -942,7 +944,7 @@ describe('DocumentsPage', () => {
it('blocks cached document content when a background refresh loses permission', () => {
documentsQuery.data = { pages: [{ items: [document()] }] }
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -1058,7 +1060,7 @@ describe('DocumentsPage', () => {
)
expect(screen.getByRole('dialog')).toBeInTheDocument()
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
const permissionAlert = screen.getByRole('alert')
@@ -1105,7 +1107,7 @@ describe('DocumentsPage', () => {
it('does not repeat the child query that already recovered from permission denial', () => {
documentsQuery.data = { pages: [{ items: [document()] }] }
tasksQuery.data = { pages: [{ items: [] }] }
- tasksQuery.error = { status: 403 }
+ tasksQuery.error = createHttpError(new Response(null, { status: 403 }))
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
tasksQuery.error = null
@@ -1127,7 +1129,7 @@ describe('DocumentsPage', () => {
await user.click(searchbox)
expect(searchbox).toHaveFocus()
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())
@@ -1149,7 +1151,7 @@ describe('DocumentsPage', () => {
).getByRole('button', { name: 'dataset.newKnowledge.reindexDocuments' })
act(() => reindex.focus())
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())
@@ -1160,7 +1162,7 @@ describe('DocumentsPage', () => {
documentsQuery.data = {
pages: [{ items: [document({ sourceId: 'unresolved-source' })], nextCursor: 'next' }],
}
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
documentsQuery.hasNextPage = true
tasksQuery.data = {
pages: [{ items: [task({ state: 'failed' })], nextCursor: 'task-next' }],
@@ -2169,7 +2171,7 @@ describe('DocumentsPage', () => {
await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.interruptTask' }))
queryClient.invalidateQueries.mockClear()
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await act(async () => resolveCancel?.(task({ id: 'revoked-action', state: 'canceled' })))
expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
@@ -2456,7 +2458,7 @@ describe('DocumentsPage', () => {
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(signals[1]?.aborted).toBe(true))
documentsQuery.error = null
@@ -2470,7 +2472,7 @@ describe('DocumentsPage', () => {
const user = userEvent.setup()
documentsQuery.data = { pages: [{ items: [document({})] }] }
tasksQuery.data = { pages: [{ items: [task({ id: 'listed-terminal-error' })] }] }
- getTaskSnapshot.mockRejectedValue(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
streamFailedTaskThenWait('listed-terminal-error')
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -2518,7 +2520,7 @@ describe('DocumentsPage', () => {
}),
)
tasksQuery.data = { pages: [{ items: [task({ id: 'forbidden-reconciliation' })] }] }
- getTaskSnapshot.mockRejectedValue(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
streamProcessingTaskEvents.mockImplementation(async function* () {
await streamGate
yield {
@@ -2567,7 +2569,7 @@ describe('DocumentsPage', () => {
vi.useFakeTimers()
documentsQuery.data = { pages: [{ items: [document()] }] }
tasksQuery.data = { pages: [{ items: [task({ id: 'denied-terminal-version' })] }] }
- getTaskSnapshot.mockRejectedValue(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
streamFailedTaskThenWait('denied-terminal-version')
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -2587,7 +2589,7 @@ describe('DocumentsPage', () => {
const user = userEvent.setup()
let rejectStream!: () => void
const streamGate = new Promise<void>((_resolve, reject) => {
- rejectStream = () => reject(new Response(null, { status: 403 }))
+ rejectStream = () => reject(createHttpError(new Response(null, { status: 403 })))
})
let resolveDocumentsRefetch!: (result: { error: null }) => void
documentsQuery.data = { pages: [{ items: [document()] }] }
@@ -2653,7 +2655,7 @@ describe('DocumentsPage', () => {
event: 'progress' as const,
id: 'lagging-denied-stream:version-2',
}
- throw new Response(null, { status: 403 })
+ throw new ORPCError('FORBIDDEN')
})
render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -2702,7 +2704,7 @@ describe('DocumentsPage', () => {
event: 'progress' as const,
id: 'same-version-terminal-retry:version-2',
}
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
}
await new Promise<void>(() => {})
})
@@ -2784,7 +2786,7 @@ describe('DocumentsPage', () => {
let streamCount = 0
streamProcessingTaskEvents.mockImplementation(async function* () {
streamCount += 1
- if (streamCount === 1) throw new Response(null, { status: 403 })
+ if (streamCount === 1) throw createHttpError(new Response(null, { status: 403 }))
await new Promise<void>(() => {})
})
@@ -2839,7 +2841,7 @@ describe('DocumentsPage', () => {
event: 'progress' as const,
id: 'recovering-stream:version-2',
}
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
}
await new Promise<void>(() => {})
})
@@ -2910,7 +2912,7 @@ describe('DocumentsPage', () => {
.mockImplementationOnce(() => new Promise(() => {}))
tasksQuery.data = { pages: [{ items: [task({ id: 'retry-document-denial' })] }] }
streamProcessingTaskEvents.mockImplementation(async function* () {
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
})
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -2919,7 +2921,7 @@ describe('DocumentsPage', () => {
})
await user.click(retry)
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())
@@ -4194,7 +4196,7 @@ describe('DocumentsPage', () => {
}
return
}
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
})
const onPermissionDenied = vi.fn()
const rendered = render(
@@ -4240,7 +4242,7 @@ describe('DocumentsPage', () => {
}
return
}
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
})
const onPermissionDenied = vi.fn()
const rendered = render(
@@ -4272,7 +4274,7 @@ describe('DocumentsPage', () => {
streamProcessingTaskEvents.mockImplementation(async function* () {
streamCount += 1
if (streamCount === 1) return
- throw new Response(null, { status: 403 })
+ throw createHttpError(new Response(null, { status: 403 }))
})
const onPermissionDenied = vi.fn()
const rendered = render(
@@ -4687,7 +4689,7 @@ describe('DocumentsPage', () => {
expect(getTaskSnapshot).toHaveBeenCalledOnce()
fireEvent.click(screen.getByRole('button', { name: 'dataset.newKnowledge.retryTask' }))
await act(async () => {})
- await act(async () => rejectPoll?.(new Response(null, { status: 403 })))
+ await act(async () => rejectPoll?.(createHttpError(new Response(null, { status: 403 }))))
tasksQuery.data = {
pages: [
@@ -4718,7 +4720,7 @@ describe('DocumentsPage', () => {
tasksQuery.data = {
pages: [{ items: [task({ id: 'forbidden-failed-poll', state: 'failed' })] }],
}
- getTaskSnapshot.mockRejectedValue(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
try {
@@ -4751,7 +4753,7 @@ describe('DocumentsPage', () => {
},
],
}
- getTaskSnapshot.mockRejectedValueOnce(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
streamProcessingTaskEvents.mockImplementation(async function* () {
await new Promise<void>(() => {})
})
@@ -4827,7 +4829,7 @@ describe('DocumentsPage', () => {
tasksQuery.data = {
pages: [{ items: [task({ id: 'removed-failed-task', state: 'failed' })] }],
}
- getTaskSnapshot.mockRejectedValue(new Response(null, { status: 403 }))
+ getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
const rendered = render(<DocumentsPage knowledgeSpaceId="space-1" />)
try {
@@ -4960,7 +4962,7 @@ describe('DocumentsPage', () => {
pages: [{ items: [task({ id: 'list-retry-after-block', state: 'failed' })] }],
}
getTaskSnapshot
- .mockRejectedValueOnce(new Response(null, { status: 403 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
.mockResolvedValueOnce(
task({
id: 'list-retry-after-block',
@@ -5029,7 +5031,7 @@ describe('DocumentsPage', () => {
],
}
getTaskSnapshot
- .mockRejectedValueOnce(new Response(null, { status: 403 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
.mockResolvedValueOnce(
task({
id: 'new-failed-generation',
@@ -5264,7 +5266,7 @@ describe('DocumentsPage', () => {
it('locks cached documents when the task query returns a permission denial', () => {
documentsQuery.data = { pages: [{ items: [document()] }] }
tasksQuery.data = { pages: [{ items: [task()] }] }
- tasksQuery.error = { status: 403 }
+ tasksQuery.error = createHttpError(new Response(null, { status: 403 }))
render(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -5353,7 +5355,7 @@ describe('DocumentsPage', () => {
],
}
getTaskSnapshot
- .mockRejectedValueOnce(new Response(null, { status: 403 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
.mockResolvedValueOnce(
task({
id: 'permission-blocked-poll',
@@ -5367,7 +5369,7 @@ describe('DocumentsPage', () => {
await act(async () => vi.advanceTimersByTime(5000))
expect(getTaskSnapshot).toHaveBeenCalledOnce()
- documentsQuery.error = { status: 403 }
+ documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
documentsQuery.error = null
rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
@@ -5420,7 +5422,9 @@ describe('DocumentsPage', () => {
it('locks uploads after a write mutation reveals revoked permission', async () => {
const user = userEvent.setup()
- uploadMutation.mutateAsync.mockRejectedValueOnce(new Response(null, { status: 403 }))
+ uploadMutation.mutateAsync.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 })),
+ )
permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
error: null,
@@ -5489,7 +5493,7 @@ describe('DocumentsPage', () => {
tasksButton.focus()
expect(tasksButton).toHaveFocus()
- await act(async () => rejectUpload(new Response(null, { status: 403 })))
+ await act(async () => rejectUpload(createHttpError(new Response(null, { status: 403 }))))
await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
expect(tasksButton).toHaveFocus()
@@ -5498,7 +5502,9 @@ describe('DocumentsPage', () => {
it('locks re-indexing after a write mutation reveals revoked permission', async () => {
const user = userEvent.setup()
documentsQuery.data = { pages: [{ items: [document()] }] }
- reindexMutation.mutateAsync.mockRejectedValueOnce(new Response(null, { status: 403 }))
+ reindexMutation.mutateAsync.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 })),
+ )
permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
error: null,
@@ -5523,7 +5529,9 @@ describe('DocumentsPage', () => {
const user = userEvent.setup()
documentsQuery.data = { pages: [{ items: [document()] }] }
tasksQuery.data = { pages: [{ items: [task()] }] }
- cancelMutation.mutateAsync.mockRejectedValueOnce(new Response(null, { status: 403 }))
+ cancelMutation.mutateAsync.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 })),
+ )
permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
error: null,
@@ -5605,9 +5613,9 @@ describe('DocumentsPage', () => {
expect(cancelMutation.mutateAsync).toHaveBeenCalledOnce()
expect(uploadMutation.mutateAsync).toHaveBeenCalledOnce()
- await act(async () => rejectUpload?.(new Response(null, { status: 403 })))
+ await act(async () => rejectUpload?.(createHttpError(new Response(null, { status: 403 }))))
await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
- await act(async () => rejectCancel?.(new Response(null, { status: 403 })))
+ await act(async () => rejectCancel?.(createHttpError(new Response(null, { status: 403 }))))
await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledTimes(2))
await act(async () =>
@@ -5678,7 +5686,7 @@ describe('DocumentsPage', () => {
tasksQuery.dataUpdatedAt = 100
tasksQuery.dataUpdateCount = 1
getTaskSnapshot
- .mockRejectedValueOnce(new Response(null, { status: 403 }))
+ .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
.mockResolvedValueOnce(
task({ id: 'denied-active-retry', state: 'running', updatedAt: taskVersion }),
)
diff --git a/web/features/new-rag/__tests__/knowledge-space-shell.spec.tsx b/web/features/new-rag/__tests__/knowledge-space-shell.spec.tsx
index 8f77d6df5b5..a3f7636a404 100644
--- a/web/features/new-rag/__tests__/knowledge-space-shell.spec.tsx
+++ b/web/features/new-rag/__tests__/knowledge-space-shell.spec.tsx
@@ -1,5 +1,6 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { KnowledgeSpaceShell } from '../knowledge-space-shell'
@@ -125,7 +126,7 @@ describe('KnowledgeSpaceShell', () => {
})
it('shows a not-found state without rendering children', () => {
- queryMock.error = { status: 404 }
+ queryMock.error = createHttpError(new Response(null, { status: 404 }))
renderWithConsoleQuery(
<KnowledgeSpaceShell knowledgeSpaceId="missing">source content</KnowledgeSpaceShell>,
@@ -135,45 +136,33 @@ describe('KnowledgeSpaceShell', () => {
expect(screen.queryByText('source content')).not.toBeInTheDocument()
})
- it('recognizes the nested status shape returned by the ORPC client', () => {
- queryMock.error = { data: { status: 404 } }
+ it('treats forbidden detail responses as a terminal non-disclosing state', () => {
+ queryMock.error = createHttpError(new Response(null, { status: 403 }))
renderWithConsoleQuery(
- <KnowledgeSpaceShell knowledgeSpaceId="missing">source content</KnowledgeSpaceShell>,
+ <KnowledgeSpaceShell knowledgeSpaceId="private">source content</KnowledgeSpaceShell>,
)
expect(screen.getByText('dataset.newKnowledge.notFoundTitle')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.retry' })).not.toBeInTheDocument()
})
- it('treats forbidden detail responses as a terminal non-disclosing state', () => {
- queryMock.error = { data: { status: 403 } }
+ it.each([403, 404])('does not automatically retry HTTP %s detail errors', (status) => {
+ const error = createHttpError(new Response(null, { status }))
+ queryMock.error = error
renderWithConsoleQuery(
<KnowledgeSpaceShell knowledgeSpaceId="private">source content</KnowledgeSpaceShell>,
)
- expect(screen.getByText('dataset.newKnowledge.notFoundTitle')).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'common.operation.retry' })).not.toBeInTheDocument()
+ const options = useQueryOptionsMock.mock.lastCall?.[0] as {
+ retry: (failureCount: number, queryError: unknown) => boolean
+ }
+ expect(options.retry(0, error)).toBe(false)
+ expect(options.retry(2, new Error('temporary failure'))).toBe(true)
+ expect(options.retry(3, new Error('temporary failure'))).toBe(false)
})
- it.each([{ status: 403 }, { data: { status: 404 } }])(
- 'does not automatically retry terminal detail errors shaped as $error',
- (error) => {
- queryMock.error = error
-
- renderWithConsoleQuery(
- <KnowledgeSpaceShell knowledgeSpaceId="private">source content</KnowledgeSpaceShell>,
- )
-
- const options = useQueryOptionsMock.mock.lastCall?.[0] as {
- retry: (failureCount: number, queryError: unknown) => boolean
- }
- expect(options.retry(0, error)).toBe(false)
- expect(options.retry(2, new Error('temporary failure'))).toBe(true)
- expect(options.retry(3, new Error('temporary failure'))).toBe(false)
- },
- )
-
it('marks Documents as the only current detail route', () => {
pathnameMock.value = '/datasets/new/space-1/documents'
queryMock.data = { id: 'space-1', name: 'Support knowledge' }
diff --git a/web/features/new-rag/__tests__/new-knowledge-list.spec.tsx b/web/features/new-rag/__tests__/new-knowledge-list.spec.tsx
index 84433110d43..f0a4f441dee 100644
--- a/web/features/new-rag/__tests__/new-knowledge-list.spec.tsx
+++ b/web/features/new-rag/__tests__/new-knowledge-list.spec.tsx
@@ -2,6 +2,7 @@ import type { KnowledgeSpaceList } from '@dify/contracts/knowledge-fs/types.gen'
import type { InfiniteData } from '@tanstack/react-query'
import { screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { renderWithNuqs } from '@/test/nuqs-testing'
import { NewKnowledgeList } from '../new-knowledge-list'
@@ -320,8 +321,21 @@ describe('NewKnowledgeList', () => {
expect(screen.getByText('dataset.newKnowledge.readOnlyEmpty')).toBeInTheDocument()
})
+ it('keeps retry available when only the error body claims the service is unavailable', async () => {
+ const user = userEvent.setup()
+ queryMock.error = createHttpError(
+ new Response(null, { status: 500 }),
+ createHttpError(new Response(null, { status: 404 })),
+ )
+ renderWithNuqs(<NewKnowledgeList view="new" onViewChange={vi.fn()} />)
+
+ expect(screen.queryByText('dataset.newKnowledge.unavailableTitle')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
+ expect(queryMock.refetch).toHaveBeenCalledOnce()
+ })
+
it.each([404, 503])('shows an unavailable state for a %s response', (status) => {
- queryMock.error = { status }
+ queryMock.error = createHttpError(new Response(null, { status }))
renderWithNuqs(<NewKnowledgeList view="new" onViewChange={vi.fn()} />)
expect(screen.getByText('dataset.newKnowledge.unavailableTitle')).toBeInTheDocument()
diff --git a/web/features/new-rag/__tests__/website-crawl-preview.spec.tsx b/web/features/new-rag/__tests__/website-crawl-preview.spec.tsx
index b817d1349f3..140df2465b2 100644
--- a/web/features/new-rag/__tests__/website-crawl-preview.spec.tsx
+++ b/web/features/new-rag/__tests__/website-crawl-preview.spec.tsx
@@ -1,6 +1,7 @@
import type { Source, SourceWorkflowRun } from '@dify/contracts/knowledge-fs/types.gen'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createHttpError } from '@/service/http-error'
import { render } from '@/test/console/render'
import { WebsiteCrawlPreview } from '../website-crawl-preview'
@@ -435,7 +436,9 @@ describe('WebsiteCrawlPreview', () => {
it('keeps the started run available when discard cancellation must be retried', async () => {
clientMock.getRun.mockReturnValue(new Promise<SourceWorkflowRun>(() => {}))
clientMock.cancel
- .mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }))
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 409 }), { message: 'conflict' }),
+ )
.mockResolvedValueOnce(run('canceled'))
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
const user = await fillValidForm()
@@ -486,7 +489,9 @@ describe('WebsiteCrawlPreview', () => {
})
.mockResolvedValueOnce({ items: [] })
clientMock.retry.mockReturnValue(retryRequest.promise)
- clientMock.cancel.mockRejectedValue(Object.assign(new Error('conflict'), { status: 409 }))
+ clientMock.cancel.mockRejectedValue(
+ createHttpError(new Response(null, { status: 409 }), { message: 'conflict' }),
+ )
render(
<>
<a href="/datasets/new/space-1/documents">Documents navigation</a>
@@ -784,7 +789,7 @@ describe('WebsiteCrawlPreview', () => {
it('only reconciles Stop while an ambiguous cancel response remains stale', async () => {
clientMock.getRun.mockResolvedValue(run('running', { progressCompleted: 1 }))
clientMock.cancel.mockRejectedValue(
- Object.assign(new Error('proxy connection lost'), { status: 502 }),
+ createHttpError(new Response(null, { status: 502 }), { message: 'proxy connection lost' }),
)
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
@@ -793,7 +798,9 @@ describe('WebsiteCrawlPreview', () => {
await screen.findByText('Getting started')
await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.stopCrawl' }))
clientMock.getRun.mockRejectedValueOnce(
- Object.assign(new Error('reconciliation unavailable'), { status: 503 }),
+ createHttpError(new Response(null, { status: 503 }), {
+ message: 'reconciliation unavailable',
+ }),
)
await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.stopCrawl' }))
await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.stopCrawl' }))
@@ -805,7 +812,9 @@ describe('WebsiteCrawlPreview', () => {
it('allows Stop to be retried after a definitive HTTP rejection', async () => {
clientMock.getRun.mockResolvedValue(run('running', { progressCompleted: 1 }))
clientMock.cancel
- .mockRejectedValueOnce(Object.assign(new Error('rate limited'), { status: 429 }))
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 429 }), { message: 'rate limited' }),
+ )
.mockResolvedValueOnce(run('canceled', { progressCompleted: 1 }))
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
@@ -943,11 +952,15 @@ describe('WebsiteCrawlPreview', () => {
.mockResolvedValueOnce(failedRun)
.mockResolvedValueOnce(failedRun)
.mockRejectedValueOnce(
- Object.assign(new Error('reconciliation unavailable'), { status: 503 }),
+ createHttpError(new Response(null, { status: 503 }), {
+ message: 'reconciliation unavailable',
+ }),
)
.mockResolvedValue(failedRun)
clientMock.getPages.mockResolvedValue({ items: [] })
- clientMock.retry.mockRejectedValue(Object.assign(new Error('proxy timeout'), { status: 504 }))
+ clientMock.retry.mockRejectedValue(
+ createHttpError(new Response(null, { status: 504 }), { message: 'proxy timeout' }),
+ )
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
const user = await fillValidForm()
@@ -969,7 +982,9 @@ describe('WebsiteCrawlPreview', () => {
)
clientMock.getPages.mockResolvedValue({ items: [] })
clientMock.retry
- .mockRejectedValueOnce(Object.assign(new Error('rate limited'), { status: 429 }))
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 429 }), { message: 'rate limited' }),
+ )
.mockResolvedValueOnce(run('running', { executionAttempts: 2 }))
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
@@ -1115,7 +1130,7 @@ describe('WebsiteCrawlPreview', () => {
it('never repeats source creation while an ambiguous result remains unreconciled', async () => {
clientMock.createSource.mockRejectedValue(
- Object.assign(new Error('proxy timeout'), { status: 504 }),
+ createHttpError(new Response(null, { status: 504 }), { message: 'proxy timeout' }),
)
clientMock.listSources.mockResolvedValue({ items: [] })
@@ -1154,7 +1169,9 @@ describe('WebsiteCrawlPreview', () => {
it('retries source creation after a definitive HTTP rejection', async () => {
clientMock.createSource
- .mockRejectedValueOnce(Object.assign(new Error('rate limited'), { status: 429 }))
+ .mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 429 }), { message: 'rate limited' }),
+ )
.mockResolvedValueOnce(source())
render(<WebsiteCrawlPreview connection={connection} knowledgeSpaceId="space-1" />)
diff --git a/web/features/new-rag/crawl-selection-form.tsx b/web/features/new-rag/crawl-selection-form.tsx
index 42ac7aa484a..0010eb04517 100644
--- a/web/features/new-rag/crawl-selection-form.tsx
+++ b/web/features/new-rag/crawl-selection-form.tsx
@@ -15,6 +15,7 @@ import { useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useRouter } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { createRequestId } from './request-id'
import { newKnowledgeDetailPath } from './routes'
@@ -44,16 +45,8 @@ const TERMINAL_IMPORT_STATES = new Set([
type PageSkipReason = 'failed' | 'off-domain'
-function requestStatus(error: unknown) {
- if (error instanceof Response) return error.status
- if (!error || typeof error !== 'object') return undefined
- if ('status' in error && typeof error.status === 'number') return error.status
- if ('data' in error && error.data && typeof error.data === 'object' && 'status' in error.data)
- return typeof error.data.status === 'number' ? error.data.status : undefined
-}
-
function isDefinitiveRequestFailure(error: unknown) {
- const status = requestStatus(error)
+ const status = getHttpErrorStatus(error)
return status !== undefined && [400, 401, 403, 404, 409, 422, 429].includes(status)
}
@@ -611,7 +604,7 @@ export function CrawlSelectionForm({
)
const policy =
policyQuery.data ??
- (requestStatus(policyQuery.error) === 404 ? initialSyncPolicy(source) : undefined)
+ (getHttpErrorStatus(policyQuery.error) === 404 ? initialSyncPolicy(source) : undefined)
if (policyQuery.isPending) {
return (
diff --git a/web/features/new-rag/create-knowledge-workflow.ts b/web/features/new-rag/create-knowledge-workflow.ts
index b6e6fe35b27..af90c6f1fb6 100644
--- a/web/features/new-rag/create-knowledge-workflow.ts
+++ b/web/features/new-rag/create-knowledge-workflow.ts
@@ -1,5 +1,6 @@
import type { KnowledgeSpaceCreationResponse } from '@dify/contracts/knowledge-fs/types.gen'
import { consoleClient } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
export const NAME_MAX_LENGTH = 160
export const DESCRIPTION_MAX_LENGTH = 2000
@@ -33,17 +34,8 @@ export class KnowledgeCreationError extends Error {
}
}
-function responseStatus(error: unknown) {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error) return error.status
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data) return data.status
- }
-}
-
export function isDefinitiveCreationRejection(error: unknown) {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status === 400 || status === 401 || status === 403 || status === 422
}
diff --git a/web/features/new-rag/document-detail-model.ts b/web/features/new-rag/document-detail-model.ts
index dbbfa7170d4..892acae8590 100644
--- a/web/features/new-rag/document-detail-model.ts
+++ b/web/features/new-rag/document-detail-model.ts
@@ -14,17 +14,6 @@ export type DocumentChunkTree = {
roots: DocumentChunkTreeNode[]
}
-export function responseStatus(error: unknown): number | undefined {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error)
- return typeof error.status === 'number' ? error.status : undefined
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data)
- return typeof data.status === 'number' ? data.status : undefined
- }
-}
-
function compareChunks(left: DocumentRevisionChunk, right: DocumentRevisionChunk) {
return left.ordinal - right.ordinal || left.id.localeCompare(right.id)
}
diff --git a/web/features/new-rag/document-detail-page.tsx b/web/features/new-rag/document-detail-page.tsx
index 14c58b2308f..225da2072f0 100644
--- a/web/features/new-rag/document-detail-page.tsx
+++ b/web/features/new-rag/document-detail-page.tsx
@@ -10,9 +10,10 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { datasetDefaultPermissionKeysAtom } from '@/context/permission-state'
import useDocumentTitle from '@/hooks/use-document-title'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { DatasetACLPermission, hasPermission } from '@/utils/permission'
import { DocumentDetailHeader } from './document-detail-header'
-import { initialDocumentRevision, responseStatus } from './document-detail-model'
+import { initialDocumentRevision } from './document-detail-model'
import { DocumentDetailStatus } from './document-detail-status'
import { DocumentRevisionContent } from './document-revision-content'
import { newKnowledgeDocumentsPath } from './routes'
@@ -70,7 +71,7 @@ export function DocumentDetailPage({
consoleQuery.knowledgeFs.getKnowledgeSpacesByIdLogicalDocumentsByDocumentId.queryOptions({
input: { params: { documentId, id: knowledgeSpaceId } },
retry: (failureCount, error) => {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status !== 403 && status !== 404 && failureCount < 2
},
}),
@@ -120,7 +121,7 @@ export function DocumentDetailPage({
consoleQuery.knowledgeFs.getKnowledgeSpacesByIdDocumentsByDocumentIdRevisionsByRevisionChunks.key()
const documentActiveRevision =
documentQuery.data?.activeRevision ?? documentQuery.data?.active?.revision ?? 0
- const documentErrorStatus = responseStatus(documentQuery.error)
+ const documentErrorStatus = getHttpErrorStatus(documentQuery.error)
const {
continueLookup,
documentMissing,
diff --git a/web/features/new-rag/documents-page.tsx b/web/features/new-rag/documents-page.tsx
index 6ce1248b031..48769be5952 100644
--- a/web/features/new-rag/documents-page.tsx
+++ b/web/features/new-rag/documents-page.tsx
@@ -24,6 +24,7 @@ import {
workspacePermissionKeysLoadingAtom,
} from '@/context/permission-state'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { DatasetACLPermission, hasPermission } from '@/utils/permission'
import { useAuxiliaryTaskReadGuard } from './auxiliary-task-read-guard'
import { DocumentBulkActions, DocumentsEmpty, DocumentsList } from './document-list'
@@ -109,19 +110,8 @@ function recoveryQueryMaskForPermissionDenials(permissionDenialMask: number) {
return recoveryQueryMask & ~permissionDenialMask
}
-function responseStatus(error: unknown): number | undefined {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error)
- return typeof error.status === 'number' ? error.status : undefined
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data)
- return typeof data.status === 'number' ? data.status : undefined
- }
-}
-
function taskSnapshotErrorIsTransient(error: unknown) {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status === undefined || status === 408 || status === 429 || status >= 500
}
@@ -237,7 +227,7 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
initialPageParam: null as string | null,
}),
)
- const documentPermissionDenied = responseStatus(documentsQuery.error) === 403
+ const documentPermissionDenied = getHttpErrorStatus(documentsQuery.error) === 403
const refetchDocumentsQuery = documentsQuery.refetch
const {
deny: denyAuxiliaryTaskRead,
@@ -290,8 +280,8 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
)
const permissionDenialMask =
(documentPermissionDenied || auxiliaryReadPermissionDenied ? DOCUMENT_PERMISSION_DENIED : 0) |
- (responseStatus(tasksQuery.error) === 403 ? TASK_PERMISSION_DENIED : 0) |
- (responseStatus(sourcesQuery.error) === 403 ? SOURCE_PERMISSION_DENIED : 0)
+ (getHttpErrorStatus(tasksQuery.error) === 403 ? TASK_PERMISSION_DENIED : 0) |
+ (getHttpErrorStatus(sourcesQuery.error) === 403 ? SOURCE_PERMISSION_DENIED : 0)
const permissionDenied = permissionDenialMask !== 0
const previousPermissionDenialMaskRef = useRef(permissionDenialMask)
const permissionRecoveryQueryMaskRef = useRef(
@@ -1112,7 +1102,7 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
} catch (error) {
if (terminalReconciliationControllersRef.current.get(taskId) !== controller) return
terminalReconciliationControllersRef.current.delete(taskId)
- if (responseStatus(error) === 403) {
+ if (getHttpErrorStatus(error) === 403) {
const currentTaskVersion = currentTaskVersionRef.current.get(taskId)
const deniedVersion =
currentTaskVersion && taskVersionIsAfter(currentTaskVersion, terminalVersion)
@@ -1507,7 +1497,7 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
else toast.success(t(($) => $['newKnowledge.documentUploadStarted']))
refreshDocumentsAndTasks()
} catch (error) {
- if (responseStatus(error) === 403) {
+ if (getHttpErrorStatus(error) === 403) {
writePermissionDenied = true
handleWritePermissionDenied()
} else toast.error(t(($) => $['newKnowledge.documentUploadFailed']))
@@ -1573,7 +1563,7 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
else toast.success(t(($) => $['newKnowledge.documentsReindexStarted']))
refreshDocumentsAndTasks()
} catch (error) {
- if (responseStatus(error) === 403) handleWritePermissionDenied()
+ if (getHttpErrorStatus(error) === 403) handleWritePermissionDenied()
else toast.error(t(($) => $['newKnowledge.documentsReindexFailed']))
} finally {
reindexPendingRef.current = false
@@ -1849,7 +1839,7 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
failedTaskPollGenerationsRef.current.get(task.id) !== requestGeneration
)
return
- if (responseStatus(error) === 403) {
+ if (getHttpErrorStatus(error) === 403) {
const currentTaskVersion = currentTaskVersionRef.current.get(task.id)
const deniedVersion =
currentTaskVersion && taskVersionIsAfter(currentTaskVersion, task.updatedAt)
@@ -2082,12 +2072,12 @@ export function DocumentsPage({ knowledgeSpaceId }: { knowledgeSpaceId: string }
>
<span className="system-xs-regular text-text-tertiary">
{t(($) =>
- responseStatus(documentsQuery.error) === 403
+ getHttpErrorStatus(documentsQuery.error) === 403
? $['newKnowledge.documentsPermissionDescription']
: $['newKnowledge.documentsErrorDescription'],
)}
</span>
- {responseStatus(documentsQuery.error) !== 403 && (
+ {getHttpErrorStatus(documentsQuery.error) !== 403 && (
<Button
ref={documentsRetryButtonRef}
aria-label={`${tCommon(($) => $['operation.retry'])} · ${t(($) => $['newKnowledge.documentsErrorDescription'])}`}
diff --git a/web/features/new-rag/knowledge-space-shell.tsx b/web/features/new-rag/knowledge-space-shell.tsx
index 2c1707c46f4..e3d6b385baf 100644
--- a/web/features/new-rag/knowledge-space-shell.tsx
+++ b/web/features/new-rag/knowledge-space-shell.tsx
@@ -18,17 +18,9 @@ import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import { usePathname } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { newKnowledgeDetailPath, newKnowledgeDocumentsPath, newKnowledgeListPath } from './routes'
-function responseStatus(error: unknown) {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error) return error.status
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data) return data.status
- }
-}
-
const knowledgeSpacePageTitle = (
pathname: string,
t: ReturnType<typeof useTranslation<'dataset'>>['t'],
@@ -64,7 +56,7 @@ export function KnowledgeSpaceShell({
input: { params: { id: knowledgeSpaceId } },
}),
retry: (failureCount, error) => {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
if (status === 403 || status === 404) return false
return failureCount < 3
@@ -92,7 +84,7 @@ export function KnowledgeSpaceShell({
)
if (knowledgeSpaceQuery.error || !knowledgeSpaceQuery.data) {
- const status = responseStatus(knowledgeSpaceQuery.error)
+ const status = getHttpErrorStatus(knowledgeSpaceQuery.error)
const notFound = status === 403 || status === 404
return (
<>
diff --git a/web/features/new-rag/new-knowledge-list.tsx b/web/features/new-rag/new-knowledge-list.tsx
index b057e121ce3..a211e297704 100644
--- a/web/features/new-rag/new-knowledge-list.tsx
+++ b/web/features/new-rag/new-knowledge-list.tsx
@@ -1,6 +1,7 @@
'use client'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
+import { ORPCError } from '@orpc/client'
import { useInfiniteQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useState } from 'react'
@@ -26,14 +27,7 @@ import {
const PAGE_SIZE = 30
function isUnavailableError(error: unknown) {
- if (!error || typeof error !== 'object') return false
- const status = 'status' in error ? error.status : undefined
- if (status === 404 || status === 503) return true
-
- const data = 'data' in error ? error.data : undefined
- if (!data || typeof data !== 'object') return false
- const dataStatus = 'status' in data ? data.status : undefined
- return dataStatus === 404 || dataStatus === 503
+ return error instanceof ORPCError && (error.status === 404 || error.status === 503)
}
function MetadataFilter({ label, onClick }: { label: string; onClick: () => void }) {
diff --git a/web/features/new-rag/processing-tasks-drawer.tsx b/web/features/new-rag/processing-tasks-drawer.tsx
index 2b16c1835e2..8771c582c68 100644
--- a/web/features/new-rag/processing-tasks-drawer.tsx
+++ b/web/features/new-rag/processing-tasks-drawer.tsx
@@ -25,6 +25,7 @@ import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { taskCanRetry, taskIsActive, taskVersionIsAfter } from './document-model'
type TaskAction = 'cancel' | 'retry'
@@ -40,17 +41,6 @@ function taskLifecycle(task: DocumentProcessingTask) {
return `${task.updatedAt}:${task.state}`
}
-function responseStatus(error: unknown): number | undefined {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error)
- return typeof error.status === 'number' ? error.status : undefined
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data)
- return typeof data.status === 'number' ? data.status : undefined
- }
-}
-
function compareTaskRecency(left: DocumentProcessingTask, right: DocumentProcessingTask) {
if (taskVersionIsAfter(left.updatedAt, right.updatedAt)) return -1
if (taskVersionIsAfter(right.updatedAt, left.updatedAt)) return 1
@@ -352,7 +342,7 @@ export function ProcessingTasksDrawer({
)
drawerCloseButtonRef.current?.focus()
} catch (error) {
- const permissionDenied = responseStatus(error) === 403
+ const permissionDenied = getHttpErrorStatus(error) === 403
if (permissionDenied) onWritePermissionDenied()
if (
!permissionDenied &&
diff --git a/web/features/new-rag/task-event-observer.tsx b/web/features/new-rag/task-event-observer.tsx
index 10addb634d2..909799450de 100644
--- a/web/features/new-rag/task-event-observer.tsx
+++ b/web/features/new-rag/task-event-observer.tsx
@@ -1,7 +1,7 @@
'use client'
-
import type { ProcessingTaskEvent } from './services/processing-task-events'
import { useEffect, useLayoutEffect, useRef } from 'react'
+import { getHttpErrorStatus } from '@/service/http-error'
import { taskVersionIsAfter } from './document-model'
import { streamProcessingTaskEvents } from './services/processing-task-events'
@@ -26,17 +26,6 @@ function waitForTaskEventReconnect(signal: AbortSignal, delay: number) {
})
}
-function responseStatus(error: unknown): number | undefined {
- if (error instanceof Response) return error.status
- if (error && typeof error === 'object' && 'status' in error)
- return typeof error.status === 'number' ? error.status : undefined
- if (error && typeof error === 'object' && 'data' in error) {
- const data = error.data
- if (data && typeof data === 'object' && 'status' in data)
- return typeof data.status === 'number' ? data.status : undefined
- }
-}
-
export function TaskEventObserver({
documentId,
knowledgeSpaceId,
@@ -110,7 +99,7 @@ export function TaskEventObserver({
}
} catch (error) {
if (controller.signal.aborted) return
- if (responseStatus(error) === 403) {
+ if (getHttpErrorStatus(error) === 403) {
if (taskVersionIsAfter(latestTaskVersionRef.current, streamTaskVersionRef.current))
streamTaskVersionRef.current = latestTaskVersionRef.current
onPermissionDenied(taskId, streamTaskVersionRef.current)
diff --git a/web/features/new-rag/use-document-reindex.ts b/web/features/new-rag/use-document-reindex.ts
index 74e974d2560..a59798b6a69 100644
--- a/web/features/new-rag/use-document-reindex.ts
+++ b/web/features/new-rag/use-document-reindex.ts
@@ -7,8 +7,8 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { refreshWorkspacePermissionKeysAfterMutationDenialAtom } from '@/context/permission-state'
import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { DatasetACLPermission, hasPermission } from '@/utils/permission'
-import { responseStatus } from './document-detail-model'
import { useDocumentTaskStatus } from './use-document-task-status'
const REINDEX_CONFIRMATION_TIMEOUT = 30000
@@ -210,7 +210,7 @@ export function useDocumentReindex({
])
toast.success(t(($) => $['newKnowledge.documentsReindexStarted']))
} catch (error) {
- if (responseStatus(error) === 403) {
+ if (getHttpErrorStatus(error) === 403) {
setWritePermissionRevoked(true)
await retryWritePermission()
}
diff --git a/web/features/new-rag/use-document-task-status.ts b/web/features/new-rag/use-document-task-status.ts
index c7db943c747..2c27580d85b 100644
--- a/web/features/new-rag/use-document-task-status.ts
+++ b/web/features/new-rag/use-document-task-status.ts
@@ -8,7 +8,7 @@ import type { InfiniteData } from '@tanstack/react-query'
import { skipToken, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useRef, useState } from 'react'
import { consoleQuery } from '@/service/console'
-import { responseStatus } from './document-detail-model'
+import { getHttpErrorStatus } from '@/service/http-error'
import { newestTaskByDocument } from './document-model'
const TASK_PAGE_SIZE = 100
@@ -116,7 +116,7 @@ export function useDocumentTaskStatus({
},
refetchOnWindowFocus: false,
retry: (failureCount, error) => {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status !== 403 && status !== 404 && failureCount < 2
},
},
@@ -167,13 +167,13 @@ export function useDocumentTaskStatus({
? ACTIVE_TASK_REFRESH_INTERVAL
: false,
retry: (failureCount, error) => {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status !== 403 && status !== 404 && failureCount < 2
},
},
),
)
- const taskSnapshotErrorStatus = responseStatus(taskSnapshotQuery.error)
+ const taskSnapshotErrorStatus = getHttpErrorStatus(taskSnapshotQuery.error)
const latestTask =
taskSnapshotErrorStatus === 403 || taskSnapshotErrorStatus === 404
? undefined
diff --git a/web/features/new-rag/website-crawl-preview.tsx b/web/features/new-rag/website-crawl-preview.tsx
index d0385af1e76..0e1d21a14ff 100644
--- a/web/features/new-rag/website-crawl-preview.tsx
+++ b/web/features/new-rag/website-crawl-preview.tsx
@@ -23,6 +23,7 @@ import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from '
import { useTranslation } from 'react-i18next'
import { useRouter } from '@/next/navigation'
import { consoleClient } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
import { registerPageLeaveGuard } from '@/utils/page-leave-guard'
import { CrawlSelectionForm } from './crawl-selection-form'
import { createRequestId } from './request-id'
@@ -104,17 +105,8 @@ function workflowAttemptKey(run: SourceWorkflowRun) {
return `${run.id}:${run.executionAttempts}`
}
-function responseStatus(error: unknown) {
- if (error instanceof Response) return error.status
- if (!error || typeof error !== 'object') return undefined
- if ('status' in error && typeof error.status === 'number') return error.status
- if ('data' in error && error.data && typeof error.data === 'object' && 'status' in error.data) {
- return typeof error.data.status === 'number' ? error.data.status : undefined
- }
-}
-
function isDefinitiveRequestFailure(error: unknown) {
- const status = responseStatus(error)
+ const status = getHttpErrorStatus(error)
return status !== undefined && [400, 401, 403, 404, 409, 422, 429].includes(status)
}
diff --git a/web/features/skills/__tests__/client.spec.ts b/web/features/skills/__tests__/client.spec.ts
new file mode 100644
index 00000000000..2d012d76d92
--- /dev/null
+++ b/web/features/skills/__tests__/client.spec.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vite-plus/test'
+import { uploadSkillFile } from '../client'
+
+vi.mock('@/app/notifications', () => ({ toast: { error: vi.fn() } }))
+
+describe('Skill upload transport failures', () => {
+ it.each([
+ ['error', 'TypeError'],
+ ['abort', 'AbortError'],
+ ['timeout', 'TimeoutError'],
+ ])('preserves the %s error type through the upload client', async (event, name) => {
+ const xhr = new XMLHttpRequest()
+ vi.spyOn(xhr, 'open').mockImplementation(() => {})
+ vi.spyOn(xhr, 'setRequestHeader').mockImplementation(() => {})
+ vi.spyOn(xhr, 'send').mockImplementation(() => xhr.dispatchEvent(new Event(event)))
+
+ await expect(
+ uploadSkillFile(new File(['content'], 'notes.md'), { xhr, onProgress: vi.fn() }),
+ ).rejects.toMatchObject({ name })
+ })
+
+ it('preserves the fetch transport network error and its cause', async () => {
+ const error = new TypeError('Failed to fetch')
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(error)
+
+ await expect(uploadSkillFile(new File(['content'], 'notes.md'))).rejects.toMatchObject({
+ name: 'NetworkError',
+ cause: error,
+ })
+ })
+})
diff --git a/web/features/skills/__tests__/detail-page-autosave.spec.tsx b/web/features/skills/__tests__/detail-page-autosave.spec.tsx
index 99179496275..34b418dd731 100644
--- a/web/features/skills/__tests__/detail-page-autosave.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-autosave.spec.tsx
@@ -1,6 +1,7 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError, httpErrorFromResponse } from '@/service/http-error'
import {
createSkillDetail,
getLiveMarkdownEditor,
@@ -74,7 +75,7 @@ describe('SkillDetailPage autosave', () => {
],
})
- const conflict = {
+ const conflict = createHttpError(new Response(null, { status: 409 }), {
code: 'skill_conflict',
details: {
current_file_hash: 'hash-2',
@@ -82,7 +83,7 @@ describe('SkillDetailPage autosave', () => {
current_file_content: latestDetail.files?.[0]?.content ?? '',
expected_updated_at: 1784638487,
},
- }
+ })
mocks.saveDraftFileMutationFn.mockRejectedValueOnce(conflict)
renderSkillDetailPage()
@@ -148,14 +149,16 @@ describe('SkillDetailPage autosave', () => {
},
],
})
- mocks.saveDraftFileMutationFn.mockRejectedValueOnce({
- code: 'skill_conflict',
- details: {
- current_file_content: latestDetail.files?.[0]?.content ?? '',
- current_updated_at: latestDetail.updated_at,
- expected_updated_at: 1784638487,
- },
- })
+ mocks.saveDraftFileMutationFn.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 409 }), {
+ code: 'skill_conflict',
+ details: {
+ current_file_content: latestDetail.files?.[0]?.content ?? '',
+ current_updated_at: latestDetail.updated_at,
+ expected_updated_at: 1784638487,
+ },
+ }),
+ )
renderSkillDetailPage()
const livePreview = await screen.findByRole('textbox', {
@@ -184,20 +187,22 @@ describe('SkillDetailPage autosave', () => {
it('uses conflict details from response errors without retrying autosave', async () => {
const user = userEvent.setup()
mocks.saveDraftFileMutationFn.mockRejectedValueOnce(
- new Response(
- JSON.stringify({
- code: 'skill_conflict',
- message: 'skill has been modified by another user',
- details: {
- current_file_hash: 'hash-2',
- current_updated_at: 1784638499,
- expected_updated_at: 1784638487,
+ await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ code: 'skill_conflict',
+ message: 'skill has been modified by another user',
+ details: {
+ current_file_hash: 'hash-2',
+ current_updated_at: 1784638499,
+ expected_updated_at: 1784638487,
+ },
+ }),
+ {
+ status: 409,
+ headers: { 'Content-Type': 'application/json' },
},
- }),
- {
- status: 409,
- headers: { 'Content-Type': 'application/json' },
- },
+ ),
),
)
renderSkillDetailPage()
@@ -227,16 +232,11 @@ describe('SkillDetailPage autosave', () => {
it('shows a save failure when conflict recovery cannot determine the latest timestamp', async () => {
const user = userEvent.setup()
- const conflict = new Error('skill has been modified by another user') as Error & {
- code: string
- details: {
- current_file_hash: string
- }
- }
- conflict.code = 'skill_conflict'
- conflict.details = {
- current_file_hash: 'hash-2',
- }
+ const conflict = createHttpError(new Response(null, { status: 409 }), {
+ code: 'skill_conflict',
+ message: 'skill has been modified by another user',
+ details: { current_file_hash: 'hash-2' },
+ })
mocks.saveDraftFileMutationFn.mockRejectedValueOnce(conflict)
mocks.skillDetailGetFn.mockRejectedValueOnce(new Error('refresh failed'))
diff --git a/web/features/skills/__tests__/detail-page-clipboard.spec.tsx b/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
index c677aa0f9b5..16f8ce1c869 100644
--- a/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
@@ -7,6 +7,7 @@ import {
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from '@/service/http-error'
import {
createDataTransfer,
createSkillDetail,
@@ -357,18 +358,14 @@ describe('SkillDetailPage clipboard', () => {
},
],
})
- const conflict = new Error('skill has been modified by another user') as Error & {
- code: string
+ const conflict = createHttpError(new Response(null, { status: 409 }), {
+ code: 'skill_conflict',
+ message: 'skill has been modified by another user',
details: {
- current_updated_at: number
- expected_updated_at: number
- }
- }
- conflict.code = 'skill_conflict'
- conflict.details = {
- current_updated_at: latestDetail.updated_at,
- expected_updated_at: 1784638487,
- }
+ current_updated_at: latestDetail.updated_at,
+ expected_updated_at: 1784638487,
+ },
+ })
mocks.saveDraftFileMutationFn
.mockRejectedValueOnce(conflict)
.mockImplementationOnce(async () => {
@@ -444,10 +441,10 @@ describe('SkillDetailPage clipboard', () => {
updated_at: 1784638491,
files: [...sourceFiles, copiedAlpha, copiedBeta],
})
- const conflict = new Error('skill has been modified by another user') as Error & {
- code: string
- }
- conflict.code = 'skill_conflict'
+ const conflict = createHttpError(new Response(null, { status: 409 }), {
+ code: 'skill_conflict',
+ message: 'skill has been modified by another user',
+ })
mocks.skillDetail = createSkillDetail({ files: sourceFiles })
mocks.saveDraftFileMutationFn
diff --git a/web/features/skills/__tests__/detail-page-uploads.spec.tsx b/web/features/skills/__tests__/detail-page-uploads.spec.tsx
index 533d9b6ed82..c775ab46b6a 100644
--- a/web/features/skills/__tests__/detail-page-uploads.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-uploads.spec.tsx
@@ -1,6 +1,7 @@
import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { httpErrorFromResponse } from '@/service/http-error'
import {
confirmUploadReview,
createDataTransfer,
@@ -239,7 +240,7 @@ describe('SkillDetailPage uploads', () => {
],
})
mocks.uploadSkillFile
- .mockRejectedValueOnce(new Error('network timeout'))
+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce({
id: 'tool-file-retry',
name: 'guide.md',
@@ -262,6 +263,10 @@ describe('SkillDetailPage uploads', () => {
})
await user.click(screen.getByRole('button', { name: /viewUploadErrors/ }))
+ expect(
+ screen.getByText('skill.skillManagement.detail.uploadNetworkFailure'),
+ ).toBeInTheDocument()
+ expect(screen.queryByText('Failed to fetch')).not.toBeInTheDocument()
await user.click(screen.getAllByRole('button', { name: 'common.operation.retry' })[0]!)
await waitFor(() => {
@@ -317,12 +322,14 @@ describe('SkillDetailPage uploads', () => {
},
],
})
- throw new Response(
- JSON.stringify({
- code: 'skill_conflict',
- message: 'skill has been modified by another user',
- }),
- { status: 409 },
+ throw await httpErrorFromResponse(
+ new Response(
+ JSON.stringify({
+ code: 'skill_conflict',
+ message: 'skill has been modified by another user',
+ }),
+ { status: 409 },
+ ),
)
})
.mockImplementationOnce(async () => {
diff --git a/web/features/skills/__tests__/page.spec.tsx b/web/features/skills/__tests__/page.spec.tsx
index 447a3c7e88d..964cf931a0c 100644
--- a/web/features/skills/__tests__/page.spec.tsx
+++ b/web/features/skills/__tests__/page.spec.tsx
@@ -10,6 +10,7 @@ import { createEvent, fireEvent, render, screen, waitFor, within } from '@testin
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { toast } from '@/app/notifications'
+import { createHttpError, httpErrorFromResponse } from '@/service/http-error'
import SkillsPage from '../page'
type SkillsInfiniteOptions = {
@@ -785,7 +786,9 @@ describe('SkillsPage', () => {
it('explains when the workspace skill limit blocks draft creation', async () => {
const user = userEvent.setup()
- mocks.createSkillMutationFn.mockRejectedValueOnce({ code: 'skill_limit_exceeded' })
+ mocks.createSkillMutationFn.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 400 }), { code: 'skill_limit_exceeded' }),
+ )
renderSkillsPage()
await user.click(await screen.findByRole('button', { name: 'skill.skillManagement.create' }))
@@ -1095,30 +1098,26 @@ describe('SkillsPage', () => {
it.each([
{
- error: {
- data: {
- body: {
- code: 'skill_name_conflict',
- details: { name: 'refund-approval' },
- },
- },
- },
+ error: createHttpError(new Response(null, { status: 409 }), {
+ code: 'skill_name_conflict',
+ details: { name: 'refund-approval' },
+ }),
message: 'skill.skillManagement.errors.nameConflict:{"name":"refund-approval"}',
},
{
- error: { code: 'skill_limit_exceeded' },
+ error: createHttpError(new Response(null, { status: 400 }), { code: 'skill_limit_exceeded' }),
message: 'skill.skillManagement.errors.workspaceLimit',
},
{
- error: { code: 'missing_skill_md' },
+ error: createHttpError(new Response(null, { status: 400 }), { code: 'missing_skill_md' }),
message: 'skill.skillManagement.errors.missingSkillMd',
},
{
- error: { message: 'Skill package must contain SKILL.md' },
+ error: new Error('Skill package must contain SKILL.md'),
message: 'skill.skillManagement.errors.missingSkillMd',
},
{
- error: { message: 'Skill name "refund-approval" already exists' },
+ error: new Error('Skill name "refund-approval" already exists'),
message: 'skill.skillManagement.errors.nameConflict:{"name":"refund-approval"}',
},
])('explains import errors for $error.code', async ({ error, message }) => {
@@ -1142,9 +1141,11 @@ describe('SkillsPage', () => {
it('keeps the package available for retry after explaining an error returned as a Response body', async () => {
const user = userEvent.setup()
mocks.importSkillMutationFn.mockRejectedValueOnce(
- new Response(JSON.stringify({ message: 'Skill package must contain SKILL.md' }), {
- status: 400,
- }),
+ await httpErrorFromResponse(
+ new Response(JSON.stringify({ message: 'Skill package must contain SKILL.md' }), {
+ status: 400,
+ }),
+ ),
)
renderSkillsPage()
const dialog = await openImportDialog(user)
diff --git a/web/features/skills/client.ts b/web/features/skills/client.ts
index eff4db7a521..868397d2bea 100644
--- a/web/features/skills/client.ts
+++ b/web/features/skills/client.ts
@@ -12,57 +12,6 @@ import type { IOnCompleted, IOnData, IOnError } from '@/service/base'
// oxlint-disable-next-line no-restricted-imports
import { get, post, ssePost, upload } from '@/service/base'
-function parseSkillUploadErrorMessage(message: string) {
- const trimmedMessage = message.trim()
- if (!trimmedMessage.startsWith('{')) return trimmedMessage
-
- try {
- const parsed: unknown = JSON.parse(trimmedMessage)
- if (parsed && typeof parsed === 'object') {
- const parsedMessage = (parsed as Record<string, unknown>).message
- if (typeof parsedMessage === 'string' && parsedMessage.trim()) return parsedMessage.trim()
- }
- } catch {
- return trimmedMessage
- }
-
- return trimmedMessage
-}
-
-function readSkillUploadErrorMessage(
- error: unknown,
- visited = new Set<unknown>(),
-): string | undefined {
- if (!error || visited.has(error)) return undefined
- if (typeof error === 'string') return parseSkillUploadErrorMessage(error)
- if (typeof error !== 'object') return undefined
-
- visited.add(error)
- const record = error as Record<string, unknown>
-
- for (const key of ['data', 'body', 'error', 'cause', 'response']) {
- const nestedMessage = readSkillUploadErrorMessage(record[key], visited)
- if (nestedMessage) return nestedMessage
- }
-
- const message = record.message
- if (typeof message === 'string' && message.trim()) return parseSkillUploadErrorMessage(message)
-
- return undefined
-}
-
-async function getSkillUploadResponseErrorMessage(response: Response) {
- try {
- const data: unknown = await response.clone().json()
- return readSkillUploadErrorMessage(data)
- } catch {
- try {
- const text = await response.clone().text()
- if (text.trim()) return parseSkillUploadErrorMessage(text)
- } catch {}
- }
-}
-
export async function uploadSkillFile(
file: File,
options?: {
@@ -73,50 +22,35 @@ export async function uploadSkillFile(
const body = new FormData()
body.append('file', file)
- try {
- if (options?.onProgress) {
- const onProgress = (event: ProgressEvent) => {
- if (!event.lengthComputable) return
-
- options.onProgress?.(Math.floor((event.loaded / event.total) * 100))
- }
-
- const response = await upload(
- {
- xhr: options.xhr ?? new XMLHttpRequest(),
- data: body,
- onprogress: onProgress,
- },
- false,
- '/workspaces/current/skills/files/upload',
- )
+ if (options?.onProgress) {
+ const onProgress = (event: ProgressEvent) => {
+ if (!event.lengthComputable) return
- return response as SkillFileUploadResponse
+ options.onProgress?.(Math.floor((event.loaded / event.total) * 100))
}
- return await post<SkillFileUploadResponse>(
- '/workspaces/current/skills/files/upload',
- { body },
+ const response = await upload(
{
- bodyStringify: false,
- deleteContentType: true,
- silent: true,
+ xhr: options.xhr ?? new XMLHttpRequest(),
+ data: body,
+ onprogress: onProgress,
},
+ false,
+ '/workspaces/current/skills/files/upload',
)
- } catch (error) {
- const message =
- error instanceof Response
- ? await getSkillUploadResponseErrorMessage(error)
- : readSkillUploadErrorMessage(error)
- if (message) {
- const normalizedError = new Error(message)
- normalizedError.cause = error
- throw normalizedError
- }
-
- throw error
+ return response as SkillFileUploadResponse
}
+
+ return await post<SkillFileUploadResponse>(
+ '/workspaces/current/skills/files/upload',
+ { body },
+ {
+ bodyStringify: false,
+ deleteContentType: true,
+ silent: true,
+ },
+ )
}
export async function fetchSkillFileBlob({
diff --git a/web/features/skills/detail/__tests__/shared.spec.ts b/web/features/skills/detail/__tests__/shared.spec.ts
index f96b5d3f96c..6b237a22801 100644
--- a/web/features/skills/detail/__tests__/shared.spec.ts
+++ b/web/features/skills/detail/__tests__/shared.spec.ts
@@ -4,9 +4,6 @@ import { consoleQuery } from '@/service/console'
import {
createUploadItemId,
deriveSkillDetailFromDraftFiles,
- getErrorCode,
- getErrorDetailNumber,
- getErrorDetailString,
getUploadFileName,
getUploadPath,
isEditableKeyboardTarget,
@@ -15,29 +12,6 @@ import {
} from '../shared'
describe('skill detail shared utilities', () => {
- it('reads error codes and details from supported error shapes', () => {
- expect(getErrorCode({ code: 'direct' })).toBe('direct')
- expect(getErrorCode({ data: { code: 'data' } })).toBe('data')
- expect(getErrorCode({ body: { code: 'body' } })).toBe('body')
- expect(getErrorCode('error')).toBeUndefined()
-
- expect(
- getErrorDetailNumber({ details: { current_updated_at: 12 } }, 'current_updated_at'),
- ).toBe(12)
- expect(
- getErrorDetailNumber({ data: { details: { current_updated_at: 13 } } }, 'current_updated_at'),
- ).toBe(13)
- expect(
- getErrorDetailString(
- { body: { details: { current_file_hash: 'hash' } } },
- 'current_file_hash',
- ),
- ).toBe('hash')
- expect(
- getErrorDetailString({ details: { current_file_hash: 1 } }, 'current_file_hash'),
- ).toBeUndefined()
- })
-
it('normalizes upload paths and names', () => {
const plainFile = new File(['guide'], 'guide.md', { type: 'text/markdown' })
const nestedFile = new File(['guide'], 'guide.md', { type: 'text/markdown' })
diff --git a/web/features/skills/detail/file-editor.tsx b/web/features/skills/detail/file-editor.tsx
index f80d5dd033f..a17d02ec43a 100644
--- a/web/features/skills/detail/file-editor.tsx
+++ b/web/features/skills/detail/file-editor.tsx
@@ -39,7 +39,6 @@ import {
findBrokenMarkdownReferenceRangeAtCaret,
findFileByPath,
findMarkdownReferenceRangeAtCaret,
- getAsyncSkillErrorPayload,
getContentEditableCaretAnchor,
getErrorCode,
getErrorDetailNumber,
@@ -370,26 +369,19 @@ export function FileEditor({
onDraftDetailChange(nextCachedDetail)
return true
} catch (error) {
- const errorPayload = await getAsyncSkillErrorPayload(error)
- if (getErrorCode(errorPayload ?? error) === 'skill_name_conflict') {
+ if (getErrorCode(error) === 'skill_name_conflict') {
toast.error(
t(($) => $['skillManagement.errors.nameConflict'], {
- name: getErrorDetailString(errorPayload ?? error, 'name') ?? '',
+ name: getErrorDetailString(error, 'name') ?? '',
}),
)
setSaveStatus('error')
return false
}
- if (getErrorCode(errorPayload ?? error) === 'skill_conflict') {
+ if (getErrorCode(error) === 'skill_conflict') {
try {
- const currentUpdatedAt = getErrorDetailNumber(
- errorPayload ?? error,
- 'current_updated_at',
- )
- const currentFileContent = getErrorDetailString(
- errorPayload ?? error,
- 'current_file_content',
- )
+ const currentUpdatedAt = getErrorDetailNumber(error, 'current_updated_at')
+ const currentFileContent = getErrorDetailString(error, 'current_file_content')
let latestDetail: SkillDetailResponse | undefined
try {
latestDetail = await refreshSkillDetailAfterConflict(queryClient, skillId, {
diff --git a/web/features/skills/detail/file-tree.tsx b/web/features/skills/detail/file-tree.tsx
index 3b8aec8e682..abc393cb16e 100644
--- a/web/features/skills/detail/file-tree.tsx
+++ b/web/features/skills/detail/file-tree.tsx
@@ -58,6 +58,7 @@ import {
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
+import { ORPCError } from '@orpc/client'
import { formatForDisplay, matchesKeyboardEvent, useHotkey } from '@tanstack/react-hotkeys'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import copy from 'copy-to-clipboard'
@@ -79,8 +80,6 @@ import {
createUploadItemId,
findFileByPath,
flattenFileTree,
- getAsyncSkillErrorMessage,
- getAsyncSkillErrorPayload,
getCopyTargetPath,
getCreatedSkillFileMimeType,
getDraggedSkillPaths,
@@ -570,12 +569,15 @@ export function FileTree({
} catch (error) {
activeUploadXhrRef.current = undefined
failedCount += 1
- const errorPayload = await getAsyncSkillErrorPayload(error)
- const errorCode = getErrorCode(errorPayload ?? error)
+
+ const errorCode = getErrorCode(error)
let failureKind: SkillUploadQueueItem['failureKind'] = 'network'
- let errorMessage =
- (await getAsyncSkillErrorMessage(error)) ??
- t(($) => $['skillManagement.detail.uploadNetworkFailure'])
+ // Transport failures and cancellation carry browser text, not a user-facing message.
+ let errorMessage = cancelUploadRef.current
+ ? tCommon(($) => $['operation.cancel'])
+ : error instanceof ORPCError
+ ? error.message
+ : t(($) => $['skillManagement.detail.uploadNetworkFailure'])
let suggestedPath: string | undefined
if (errorCode === 'skill_conflict') {
failureKind = 'conflict'
@@ -908,9 +910,7 @@ export function FileTree({
copiedTargetPaths.push(targetPath)
break
} catch (error) {
- const errorPayload = await getAsyncSkillErrorPayload(error)
- if (hasRetriedConflict || getErrorCode(errorPayload ?? error) !== 'skill_conflict')
- throw error
+ if (hasRetriedConflict || getErrorCode(error) !== 'skill_conflict') throw error
latestDetail = await refreshSkillDetailAfterConflict(queryClient, skillId)
fileMutationCoordinator.latestDetail = latestDetail
diff --git a/web/features/skills/detail/shared.tsx b/web/features/skills/detail/shared.tsx
index 93232dbdf22..cb07dec6e9d 100644
--- a/web/features/skills/detail/shared.tsx
+++ b/web/features/skills/detail/shared.tsx
@@ -17,6 +17,7 @@ import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { toast } from '@/app/notifications'
import { getFileIconType } from '@/features/agent-v2/file-icon'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import {
getSkillErrorCode,
getSkillErrorDetailNumber,
@@ -1340,82 +1341,8 @@ function getDraftSkillName(parsedSkillMd: ParsedMarkdownContent, displayName: st
return generatedName || undefined
}
-function parseServerMessage(message: string) {
- const trimmedMessage = message.trim()
- if (!trimmedMessage.startsWith('{')) return trimmedMessage
-
- try {
- const parsed: unknown = JSON.parse(trimmedMessage)
- if (parsed && typeof parsed === 'object') {
- const parsedMessage = (parsed as Record<string, unknown>).message
- if (typeof parsedMessage === 'string' && parsedMessage.trim()) return parsedMessage.trim()
- }
- } catch {
- return trimmedMessage
- }
-
- return trimmedMessage
-}
-
-async function readSkillResponseErrorMessage(response: Response) {
- try {
- const data: unknown = await response.clone().json()
- return getSkillErrorMessage(data)
- } catch {
- try {
- const text = await response.clone().text()
- if (text.trim()) return parseServerMessage(text)
- } catch {}
- }
-}
-
-async function readSkillResponseErrorPayload(response: Response) {
- try {
- const data: unknown = await response.clone().json()
- return isRecord(data) ? data : undefined
- } catch {
- return undefined
- }
-}
-
-function getSkillErrorMessage(error: unknown, visited = new Set<unknown>()): string | undefined {
- if (error instanceof Response) return undefined
- if (!error || visited.has(error)) return undefined
- if (typeof error === 'string') return parseServerMessage(error)
- if (typeof error !== 'object') return undefined
-
- visited.add(error)
- const record = error as Record<string, unknown>
-
- for (const key of ['data', 'body', 'error', 'cause', 'response']) {
- const nestedMessage = getSkillErrorMessage(record[key], visited)
- if (nestedMessage) return nestedMessage
- }
-
- const message = record.message
- if (typeof message === 'string' && message.trim()) return parseServerMessage(message)
-
- return undefined
-}
-
-export async function getAsyncSkillErrorMessage(error: unknown) {
- if (error instanceof Response) return readSkillResponseErrorMessage(error)
-
- return getSkillErrorMessage(error)
-}
-
-export async function getAsyncSkillErrorPayload(error: unknown) {
- if (error instanceof Response) return readSkillResponseErrorPayload(error)
-
- return isRecord(error) ? error : undefined
-}
-
export function showSkillErrorToast(error: unknown, fallbackMessage: string) {
- void showSkillErrorToastAsync(error, fallbackMessage)
-}
-
-async function showSkillErrorToastAsync(error: unknown, fallbackMessage: string) {
- toast.error((await getAsyncSkillErrorMessage(error)) ?? fallbackMessage)
+ toast.error(getErrorMessage(error) ?? fallbackMessage)
}
export function getSkillCodeLanguage(file: SkillFileResponse | undefined) {
diff --git a/web/features/skills/detail/skill-display-name-editor.tsx b/web/features/skills/detail/skill-display-name-editor.tsx
index 37491509b34..054051c05b5 100644
--- a/web/features/skills/detail/skill-display-name-editor.tsx
+++ b/web/features/skills/detail/skill-display-name-editor.tsx
@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import {
- getAsyncSkillErrorPayload,
getErrorCode,
getErrorDetailString,
invalidateSkillDetail,
@@ -103,11 +102,11 @@ export function SkillDisplayNameEditor({
onEditingChange(false)
} catch (error) {
setDraftName(displayName)
- const errorPayload = await getAsyncSkillErrorPayload(error)
- if (getErrorCode(errorPayload ?? error) === 'skill_name_conflict') {
+
+ if (getErrorCode(error) === 'skill_name_conflict') {
toast.error(
t(($) => $['skillManagement.errors.nameConflict'], {
- name: getErrorDetailString(errorPayload ?? error, 'name') ?? '',
+ name: getErrorDetailString(error, 'name') ?? '',
}),
)
} else {
diff --git a/web/features/skills/error.ts b/web/features/skills/error.ts
index e528fa5dc4f..383d4645eb0 100644
--- a/web/features/skills/error.ts
+++ b/web/features/skills/error.ts
@@ -1,48 +1,26 @@
+import { ORPCError } from '@orpc/client'
+
export function isSkillErrorRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
-export async function normalizeSkillError(error: unknown): Promise<unknown> {
- if (!(error instanceof Response)) return error
-
- try {
- return await error.clone().json()
- } catch {
- return error
- }
-}
-
export function getSkillErrorCode(error: unknown): string | undefined {
- if (!isSkillErrorRecord(error)) return undefined
+ if (!(error instanceof Error)) return undefined
- const data = isSkillErrorRecord(error.data) ? error.data : undefined
- const candidates = [error, data, error.body, data?.body]
- for (const candidate of candidates) {
- if (isSkillErrorRecord(candidate) && typeof candidate.code === 'string') return candidate.code
- }
+ if (error instanceof ORPCError && error.code !== 'HTTP_ERROR') return error.code
- const messages = candidates.flatMap((candidate) => {
- if (!isSkillErrorRecord(candidate)) return []
- return typeof candidate.message === 'string' ? [candidate.message] : []
- })
- if (messages.some((message) => /must contain SKILL\.md/i.test(message))) return 'missing_skill_md'
- if (messages.some((message) => /skill name .+ already exists/i.test(message)))
- return 'skill_name_conflict'
- if (messages.some((message) => /skill limit/i.test(message))) return 'skill_limit_exceeded'
+ // Legacy package validation still reports these failures through message text.
+ const message = error.message
+ if (/must contain SKILL\.md/i.test(message)) return 'missing_skill_md'
+ if (/skill name .+ already exists/i.test(message)) return 'skill_name_conflict'
+ if (/skill limit/i.test(message)) return 'skill_limit_exceeded'
return undefined
}
function getSkillErrorDetails(error: unknown): Record<string, unknown> | undefined {
- if (!isSkillErrorRecord(error)) return undefined
-
- const data = isSkillErrorRecord(error.data) ? error.data : undefined
- const candidates = [error, data, error.body, data?.body]
- for (const candidate of candidates) {
- if (isSkillErrorRecord(candidate) && isSkillErrorRecord(candidate.details))
- return candidate.details
- }
-
+ if (error instanceof ORPCError && isSkillErrorRecord(error.data))
+ return isSkillErrorRecord(error.data.details) ? error.data.details : undefined
return undefined
}
@@ -54,15 +32,8 @@ export function getSkillErrorDetailNumber(error: unknown, key: string): number |
export function getSkillErrorDetailString(error: unknown, key: string): string | undefined {
const value = getSkillErrorDetails(error)?.[key]
if (typeof value === 'string') return value
- if (key !== 'name' || !isSkillErrorRecord(error)) return undefined
+ if (key !== 'name' || !(error instanceof Error)) return undefined
- const data = isSkillErrorRecord(error.data) ? error.data : undefined
- const candidates = [error, data, error.body, data?.body]
- for (const candidate of candidates) {
- if (!isSkillErrorRecord(candidate) || typeof candidate.message !== 'string') continue
- const match = candidate.message.match(/skill name ["']?(.+?)["']? already exists/i)
- if (match?.[1]) return match[1]
- }
-
- return undefined
+ if (typeof error.message !== 'string') return undefined
+ return error.message.match(/skill name ["']?(.+?)["']? already exists/i)?.[1]
}
diff --git a/web/features/skills/page.tsx b/web/features/skills/page.tsx
index d2dbc8ee0a1..a9c167f2469 100644
--- a/web/features/skills/page.tsx
+++ b/web/features/skills/page.tsx
@@ -58,7 +58,7 @@ import { downloadBlob } from '@/utils/download'
import { formatFileSize } from '@/utils/format'
import { fetchSkillArchiveBlob } from './client'
import { SkillReferencesList, SkillReferencesListSkeleton } from './detail/skill-metadata'
-import { getSkillErrorCode, getSkillErrorDetailString, normalizeSkillError } from './error'
+import { getSkillErrorCode, getSkillErrorDetailString } from './error'
import { useSkillPermissions } from './permissions'
import { skillKeywordQueryParser, skillQueryParamNames, skillTagQueryParser } from './query-params'
import { SkillListTagManagementModal } from './skill-list-tag-management-modal'
@@ -1056,10 +1056,9 @@ export default function SkillsPage() {
invalidateSkillListQueries(queryClient)
router.push(`/skills/${skill.id}`)
},
- onError: async (error) => {
- const normalizedError = await normalizeSkillError(error)
+ onError: (error) => {
toast.error(
- getSkillErrorCode(normalizedError) === 'skill_limit_exceeded'
+ getSkillErrorCode(error) === 'skill_limit_exceeded'
? t(($) => $['skillManagement.errors.workspaceLimit'])
: t(($) => $['skillManagement.createFailed']),
)
@@ -1083,13 +1082,12 @@ export default function SkillsPage() {
invalidateSkillListQueries(queryClient)
router.push(`/skills/${skill.id}`)
},
- onError: async (error) => {
- const normalizedError = await normalizeSkillError(error)
- const errorCode = getSkillErrorCode(normalizedError)
+ onError: (error) => {
+ const errorCode = getSkillErrorCode(error)
if (errorCode === 'skill_name_conflict') {
toast.error(
t(($) => $['skillManagement.errors.nameConflict'], {
- name: getSkillErrorDetailString(normalizedError, 'name') ?? '',
+ name: getSkillErrorDetailString(error, 'name') ?? '',
}),
)
return
diff --git a/web/hooks/use-import-dsl.spec.tsx b/web/hooks/use-import-dsl.spec.tsx
index 3bb15d54bc5..9ed470e595d 100644
--- a/web/hooks/use-import-dsl.spec.tsx
+++ b/web/hooks/use-import-dsl.spec.tsx
@@ -1,5 +1,6 @@
import { act, render, screen, waitFor } from '@testing-library/react'
import { DSLImportMode, DSLImportStatus } from '@/models/app'
+import { httpErrorFromResponse } from '@/service/http-error'
import { renderHookWithConsoleQuery } from '@/test/console/query-data'
import { AppModeEnum } from '@/types/app'
import { useImportDSL } from './use-import-dsl'
@@ -275,12 +276,12 @@ describe('useImportDSL', () => {
() => Response.json({ message: 'Missing app section' }, { status: 400 }),
'Missing app section',
],
- ['empty', () => new Response(null, { status: 500 }), undefined],
- ['HTML', () => new Response('<html>Bad gateway</html>', { status: 502 }), undefined],
+ ['empty', () => new Response(null, { status: 500 }), 'HTTP 500'],
+ ['HTML', () => new Response('<html>Bad gateway</html>', { status: 502 }), 'HTTP 502'],
] as const)(
'shows one failure toast for a %s import response',
async (_, response, description) => {
- mockImportDSL.mockRejectedValue(response())
+ mockImportDSL.mockRejectedValue(await httpErrorFromResponse(response()))
const onFailed = vi.fn()
const { result } = renderHookWithConsoleQuery(() => useImportDSL())
@@ -360,7 +361,9 @@ describe('useImportDSL', () => {
it('shows the backend error when confirmation rejects with an HTTP response', async () => {
mockImportDSL.mockResolvedValue({ id: 'import-1', status: DSLImportStatus.PENDING })
mockImportDSLConfirm.mockRejectedValue(
- Response.json({ error: 'Import confirmation expired' }, { status: 400 }),
+ await httpErrorFromResponse(
+ Response.json({ error: 'Import confirmation expired' }, { status: 400 }),
+ ),
)
const onFailed = vi.fn()
const { result } = renderHookWithConsoleQuery(() => useImportDSL())
diff --git a/web/hooks/use-import-dsl.ts b/web/hooks/use-import-dsl.ts
index 401ac79fe63..9484e2ff8db 100644
--- a/web/hooks/use-import-dsl.ts
+++ b/web/hooks/use-import-dsl.ts
@@ -4,7 +4,6 @@ import { useAtomValue } from 'jotai'
import { createElement, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import DSLImportWarningDescription from '@/app/components/app/create-from-dsl-modal/dsl-import-warning-description'
-import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
@@ -14,6 +13,7 @@ import { DSLImportStatus } from '@/models/app'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { getRedirection } from '@/utils/app-redirection'
+import { getErrorMessage } from '@/utils/error-message'
import { resolveImportedAppRedirectionTarget } from '@/utils/imported-app-redirection'
type ResponseCallback = {
@@ -126,7 +126,7 @@ export const useImportDSL = () => {
toast.error(
t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
onFailed?.()
@@ -215,7 +215,7 @@ export const useImportDSL = () => {
toast.error(
t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
{
- description: await getAppTransferErrorMessage(error),
+ description: getErrorMessage(error),
},
)
onFailed?.()
diff --git a/web/service/__tests__/base-request.spec.ts b/web/service/__tests__/base-request.spec.ts
index 423232f1069..f0e14038e7d 100644
--- a/web/service/__tests__/base-request.spec.ts
+++ b/web/service/__tests__/base-request.spec.ts
@@ -30,17 +30,6 @@ vi.mock('@/utils/var', () => ({
basePath: '/app',
}))
-vi.mock('../fetch', () => ({
- base: mocks.baseFetch,
- ContentType: {
- audio: 'audio/mpeg',
- download: 'application/octet-stream',
- downloadZip: 'application/zip',
- json: 'application/json',
- },
- getBaseOptions: vi.fn(() => ({})),
-}))
-
vi.mock('../refresh-token', () => ({
refreshAccessTokenOrReLogin: mocks.refreshAccessTokenOrReLogin,
}))
@@ -55,6 +44,7 @@ vi.mock('../webapp-auth', () => ({
clearWebAppPassport: mocks.clearWebAppPassport,
completeWebAppAuthorizationRecovery: mocks.completeWebAppAuthorizationRecovery,
getWebAppPassport: vi.fn(() => ''),
+ getWebAppAccessToken: vi.fn(() => ''),
}))
const createUnauthorizedResponse = () =>
@@ -93,7 +83,7 @@ type ClientRequestOptions = {
}
function arrangeClientRequest({ response, refreshError }: ClientRequestOptions) {
- mocks.baseFetch.mockRejectedValue(response)
+ mocks.baseFetch.mockResolvedValue(response)
if (refreshError) mocks.refreshAccessTokenOrReLogin.mockRejectedValue(refreshError)
}
@@ -103,6 +93,7 @@ describe('request 401 handling', () => {
beforeEach(() => {
mocks.isClient = true
mocks.baseFetch.mockReset()
+ vi.stubGlobal('fetch', mocks.baseFetch)
mocks.beginWebAppAuthorizationRecovery.mockReset()
mocks.beginWebAppAuthorizationRecovery.mockReturnValue(true)
mocks.clearWebAppPassport.mockReset()
@@ -136,9 +127,12 @@ describe('request 401 handling', () => {
it('should not run browser auth recovery when handling 401 on the server', async () => {
const response = createUnauthorizedResponse()
mocks.isClient = false
- mocks.baseFetch.mockRejectedValue(response)
+ mocks.baseFetch.mockResolvedValue(response)
- await expect(request('/account/profile')).rejects.toBe(response)
+ await expect(request('/account/profile')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(mocks.refreshAccessTokenOrReLogin).not.toHaveBeenCalled()
})
@@ -148,7 +142,10 @@ describe('request 401 handling', () => {
arrangeClientRequest({ response })
window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-a-marker')
- await expect(request('/account/profile')).rejects.toBe(response)
+ await expect(request('/account/profile')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(globalThis.location.href).toBe(
`https://example.com/app/signin?redirect_url=${encodeURIComponent('/app/apps?category=agent#recent')}`,
@@ -168,7 +165,10 @@ describe('request 401 handling', () => {
})
globalThis.location.reload = reload
- await expect(request('/account/profile')).rejects.toBe(response)
+ await expect(request('/account/profile')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(reload).toHaveBeenCalledOnce()
window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-b-marker')
@@ -183,7 +183,10 @@ describe('request 401 handling', () => {
})
window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-a-marker')
- await expect(request('/account/profile')).rejects.toBe(response)
+ await expect(request('/account/profile')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(mocks.refreshAccessTokenOrReLogin).toHaveBeenCalledOnce()
expect(globalThis.location.href).toBe(
@@ -197,7 +200,10 @@ describe('request 401 handling', () => {
arrangeClientRequest({ response })
window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'console-marker')
- await expect(request('/account/profile', {}, { isPublicAPI: true })).rejects.toBe(response)
+ await expect(request('/account/profile', {}, { isPublicAPI: true })).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe('console-marker')
})
@@ -215,7 +221,10 @@ describe('request 401 handling', () => {
mocks.resolveWebAppAddress.mockReturnValue(address)
arrangeClientRequest({ response })
- await expect(request('/messages')).rejects.toBe(response)
+ await expect(request('/messages')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(mocks.clearWebAppPassport).toHaveBeenCalledWith(address)
expect(globalThis.location.reload).toHaveBeenCalledOnce()
@@ -225,7 +234,7 @@ describe('request 401 handling', () => {
it('should complete authorization recovery after an environment request succeeds', async () => {
const address = { kind: 'environment', code: 'environment-code' } as const
mocks.resolveWebAppAddress.mockReturnValue(address)
- mocks.baseFetch.mockResolvedValue({ app_id: 'app-id' })
+ mocks.baseFetch.mockImplementation(async () => Response.json({ app_id: 'app-id' }))
await request('/site', {}, { isPublicAPI: true })
@@ -235,7 +244,7 @@ describe('request 401 handling', () => {
it('should keep authorization recovery pending after passport succeeds', async () => {
const address = { kind: 'environment', code: 'environment-code' } as const
mocks.resolveWebAppAddress.mockReturnValue(address)
- mocks.baseFetch.mockResolvedValue({ access_token: 'passport' })
+ mocks.baseFetch.mockResolvedValue(Response.json({ access_token: 'passport' }))
await request('/passport', {}, { isPublicAPI: true })
@@ -280,7 +289,10 @@ describe('request 401 handling', () => {
mocks.beginWebAppAuthorizationRecovery.mockReturnValue(false)
arrangeClientRequest({ response })
- await expect(request('/site')).rejects.toBe(response)
+ await expect(request('/site')).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(mocks.clearWebAppPassport).not.toHaveBeenCalled()
expect(globalThis.location.reload).not.toHaveBeenCalled()
@@ -321,7 +333,10 @@ describe('request 401 handling', () => {
mocks.resolveWebAppAddress.mockReturnValue(address)
arrangeClientRequest({ response })
- await expect(request('/messages', {}, { isPublicAPI: true })).rejects.toBe(response)
+ await expect(request('/messages', {}, { isPublicAPI: true })).rejects.toMatchObject({
+ defined: false,
+ status: response.status,
+ })
expect(globalThis.location.href).toContain('/webapp-signin?')
expect(globalThis.location.href).toContain('code=403')
@@ -335,6 +350,7 @@ describe('request 401 handling', () => {
const xhr = {
open: vi.fn(),
setRequestHeader: vi.fn(),
+ getAllResponseHeaders: vi.fn(() => ''),
send: vi.fn(function (this: { onreadystatechange?: () => void }) {
this.onreadystatechange?.()
}),
@@ -350,7 +366,11 @@ describe('request 401 handling', () => {
responseType: '',
} as unknown as XMLHttpRequest
- await expect(upload({ xhr, data: new FormData() }, true)).rejects.toBe(xhr)
+ await expect(upload({ xhr, data: new FormData() }, true)).rejects.toMatchObject({
+ defined: false,
+ status: 401,
+ data: { reason: 'APPDEPLOY_WEB_APP_ACCESS_DENIED' },
+ })
expect(globalThis.location.href).toContain('/webapp-signin?')
expect(globalThis.location.href).toContain('code=403')
diff --git a/web/service/base.ts b/web/service/base.ts
index a50169071d6..5133179383d 100644
--- a/web/service/base.ts
+++ b/web/service/base.ts
@@ -1,4 +1,4 @@
-import type { FetchOptionType, ResponseError } from './fetch'
+import type { FetchOptionType } from './fetch'
import type { MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/base/chat/chat/type'
import type { VisionFile } from '@/types/app'
import type {
@@ -28,6 +28,7 @@ import type {
WorkflowPausedResponse,
WorkflowStartedResponse,
} from '@/types/workflow'
+import { ORPCError } from '@orpc/client'
import Cookies from 'js-cookie'
import { discardRegistrationSessionState } from '@/app/components/base/amplitude/registration-session-state'
import { toast } from '@/app/notifications'
@@ -44,6 +45,7 @@ import { isClient } from '@/utils/client'
import { resolveLoginRedirectTarget } from '@/utils/login-redirect'
import { basePath } from '@/utils/var'
import { base, ContentType, getBaseOptions } from './fetch'
+import { httpErrorFromXhr, isHttpErrorStatus, isTransientHttpError } from './http-error'
import { refreshAccessTokenOrReLogin } from './refresh-token'
import { getWebAppPublicApiPath, resolveWebAppAddress } from './webapp-address'
import {
@@ -59,7 +61,7 @@ const isWebAppAuthorizationEndpoint = (url: string) =>
/\/(?:login(?:\/|\?|$)|passport(?:\?|$))/.test(url)
const recoverEnvironmentWebAppAuthorization = (
- error: { code?: string | number; message?: string; reason?: string },
+ error: { code?: string | number; message?: string; reason?: unknown },
url?: string,
) => {
const address = resolveWebAppAddress()
@@ -81,7 +83,7 @@ const recoverEnvironmentWebAppAuthorization = (
}
const handleWebAppAuthorizationError = (
- error: { code?: string | number; message?: string; reason?: string },
+ error: { code?: string | number; message?: string; reason?: unknown },
url?: string,
) => {
if (
@@ -156,7 +158,7 @@ const handlePublicStreamResponseError = async (
onNotifyError: IOnError | undefined,
silent: boolean | undefined,
) => {
- let data: { code?: string; message?: string; reason?: string } | undefined
+ let data: { code?: string; message?: string; reason?: unknown } | undefined
try {
data = (await response.clone().json()) as typeof data
} catch {}
@@ -625,8 +627,8 @@ export const upload = async (
xhr.withCredentials = true
xhr.responseType = 'json'
xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- if (xhr.status === 201) resolve(xhr.response)
+ if (xhr.readyState === 4 && xhr.status !== 0) {
+ if (!isHttpErrorStatus(xhr.status)) resolve(xhr.response)
else {
if (
isPublicAPI &&
@@ -635,10 +637,13 @@ export const upload = async (
xhr.response !== null
)
handleWebAppAuthorizationError(xhr.response)
- reject(xhr)
+ reject(httpErrorFromXhr(xhr))
}
}
}
+ xhr.onerror = () => reject(new TypeError('Failed to fetch'))
+ xhr.onabort = () => reject(new DOMException('The operation was aborted.', 'AbortError'))
+ xhr.ontimeout = () => reject(new DOMException('The operation timed out.', 'TimeoutError'))
if (mergedOptions.onprogress) xhr.upload.onprogress = mergedOptions.onprogress
xhr.send(mergedOptions.data)
})
@@ -1079,19 +1084,18 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
completeWebAppAuthorizationRecovery(address)
return resp
}
- const errResp: Response = err as any
- if (errResp.status === 401 || (errResp.status === 403 && isPublicAPI)) {
+ if (err instanceof ORPCError && (err.status === 401 || (err.status === 403 && isPublicAPI))) {
if (!isClient) return Promise.reject(err)
- const [parseErr, errRespData] = await asyncRunSafe<ResponseError>(errResp.json())
- if (parseErr) {
- if (errResp.status === 401) {
+ const errRespData = { code: err.code, message: err.message, reason: err.data?.reason }
+ if (!err.data) {
+ if (err.status === 401) {
discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)
window.location.href = buildSigninUrlWithRedirect()
}
return Promise.reject(err)
}
- if (/\/login/.test(url)) return Promise.reject(errRespData)
+ if (/\/login/.test(url)) return Promise.reject(err)
if (handleWebAppAuthorizationError(errRespData, url)) return Promise.reject(err)
// special code
const { code, message } = errRespData
@@ -1099,7 +1103,7 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
requiredWebSSOLogin()
return Promise.reject(err)
}
- if (errResp.status === 403) return Promise.reject(err)
+ if (err.status === 403) return Promise.reject(err)
if (code === 'unauthorized_and_force_logout') {
// Cookies will be cleared by the backend
discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)
@@ -1126,6 +1130,8 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
// refresh token
const [refreshErr] = await asyncRunSafe(refreshAccessTokenOrReLogin(TIME_OUT))
if (refreshErr === null) return baseFetch<T>(url, options, otherOptionsForBaseFetch)
+ // Preserve the transient failure so callers can retry instead of treating the session as ended.
+ if (isTransientHttpError(refreshErr)) return Promise.reject(refreshErr)
// /device is the device-flow chooser; logged-out is a valid state
// there. Redirecting to /signin loses the user_code context and
// the post-login flow lands on /apps instead of returning here.
diff --git a/web/service/console/client.spec.ts b/web/service/console/client.spec.ts
index 636bb6f6771..6fa2f07111e 100644
--- a/web/service/console/client.spec.ts
+++ b/web/service/console/client.spec.ts
@@ -545,7 +545,8 @@ describe('consoleQuery agent query defaults', () => {
})
const retry = getRetryFn(queryOptions)
- expect(retry(0, new Response(null, { status: 404 }))).toBe(false)
+ const { createHttpError } = await import('@/service/http-error')
+ expect(retry(0, createHttpError(new Response(null, { status: 404 })))).toBe(false)
})
it('should retry other agent detail errors fewer than three times', async () => {
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index 8bb994aab71..dadc6b019d6 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -9,6 +9,7 @@ import type { RouterUtils } from '@orpc/tanstack-query'
import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import type { ConsoleClient } from './index'
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
+import { isNotFoundError } from '@/service/http-error'
export function createConsoleQuery(consoleClient: ConsoleClient) {
const consoleQuery: RouterUtils<ConsoleClient> = createTanstackQueryUtils(consoleClient, {
@@ -796,7 +797,7 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
get: {
queryOptions: {
retry: (failureCount, error) => {
- if (error instanceof Response && error.status === 404) return false
+ if (isNotFoundError(error)) return false
return failureCount < 3
},
@@ -837,7 +838,7 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
get: {
queryOptions: {
retry: (failureCount, error) => {
- if (error instanceof Response && error.status === 404) return false
+ if (isNotFoundError(error)) return false
return failureCount < 3
},
diff --git a/web/service/console/server.spec.ts b/web/service/console/server.spec.ts
index 1e7bd86918e..aa993e419a9 100644
--- a/web/service/console/server.spec.ts
+++ b/web/service/console/server.spec.ts
@@ -41,6 +41,75 @@ beforeEach(() => {
})
describe('server console oRPC client', () => {
+ it('preserves cancellation after receiving HTTP error headers', async () => {
+ const controller = new AbortController()
+ const abortError = new DOMException('Cancelled while reading the response', 'AbortError')
+ let resolveBodyRead: () => void
+ const bodyRead = new Promise<void>((resolve) => {
+ resolveBodyRead = resolve
+ })
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async (request: Request) =>
+ new Response(
+ new ReadableStream(
+ {
+ start(body) {
+ request.signal.addEventListener(
+ 'abort',
+ () => body.error(request.signal.reason),
+ { once: true },
+ )
+ },
+ pull() {
+ resolveBodyRead()
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ { status: 403 },
+ ),
+ ),
+ )
+ await import('./server')
+ const { consoleClient } = await import('@/service/console')
+ const pending = consoleClient.systemFeatures
+ .get({}, { signal: controller.signal })
+ .catch((error: unknown) => error)
+ await bodyRead
+ controller.abort(abortError)
+
+ expect(await pending).toBe(abortError)
+ })
+
+ it('preserves HTTP status and server error details through the server transport', async () => {
+ const { ORPCError } = await import('@orpc/client')
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ Response.json(
+ {
+ code: 'forbidden',
+ message: 'Workspace access denied',
+ details: { request_id: 'server-123' },
+ },
+ { status: 403 },
+ ),
+ ),
+ )
+ await import('./server')
+ const { consoleClient } = await import('@/service/console')
+ const error = await consoleClient.systemFeatures.get().catch((error: unknown) => error)
+ expect(error).toBeInstanceOf(ORPCError)
+ expect(error).toMatchObject({
+ status: 403,
+ code: 'forbidden',
+ message: 'Workspace access denied',
+ data: { details: { request_id: 'server-123' } },
+ })
+ })
+
it('should resolve server console API URLs only from configured or absolute prefixes', async () => {
const { resolveServerConsoleApiPrefix, resolveServerConsoleApiUrl } = await import('./server')
diff --git a/web/service/console/server.ts b/web/service/console/server.ts
index c9e6425e256..9b623de9d99 100644
--- a/web/service/console/server.ts
+++ b/web/service/console/server.ts
@@ -7,6 +7,7 @@ import { cache } from 'react'
import { API_PREFIX, CSRF_COOKIE_NAME, CSRF_HEADER_NAME } from '@/config'
import { SERVER_CONSOLE_API_PREFIX } from '@/config/server'
import { cookies, headers } from '@/next/headers'
+import { httpErrorFromResponse, isHttpErrorStatus } from '@/service/http-error'
import { createConsoleContractLink } from './contract-loader'
import { normalizeConsoleOpenAPIURL } from './openapi-url'
import 'server-only'
@@ -65,17 +66,19 @@ function createServerConsoleOpenAPILink(
return new OpenAPILink<ConsoleClientContext>(contract, {
url: getServerConsoleApiPrefix,
headers: getServerConsoleRequestHeaders,
- fetch: (request, init) => {
+ fetch: async (request, init) => {
if (request.body && !request.headers.has('content-type'))
request.headers.set('Content-Type', 'application/json')
const normalizedURL = normalizeConsoleOpenAPIURL(request.url)
const normalizedRequest =
normalizedURL === request.url ? request : new Request(normalizedURL, request)
- return globalThis.fetch(normalizedRequest, {
+ const response = await globalThis.fetch(normalizedRequest, {
...init,
cache: 'no-store',
})
+ if (isHttpErrorStatus(response.status)) throw await httpErrorFromResponse(response)
+ return response
},
interceptors: [
onError((error) => {
diff --git a/web/service/fetch.spec.ts b/web/service/fetch.spec.ts
index e74a774911b..f748d024002 100644
--- a/web/service/fetch.spec.ts
+++ b/web/service/fetch.spec.ts
@@ -1,3 +1,4 @@
+import { ORPCError } from '@orpc/client'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { PUBLIC_API_PREFIX } from '@/config'
import {
@@ -134,8 +135,8 @@ describe('base', () => {
}
// Assert
- expect(caughtError).toBeInstanceOf(Response)
- await expect((caughtError as Response).json()).resolves.toEqual({
+ expect(caughtError).toBeInstanceOf(ORPCError)
+ expect(caughtError).toMatchObject({
code: 'unauthorized',
message: 'Unauthorized',
status: 401,
@@ -159,7 +160,7 @@ describe('base', () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(errorResponse)
- await expect(base('/imports')).rejects.toBeInstanceOf(Response)
+ await expect(base('/imports')).rejects.toBeInstanceOf(ORPCError)
expect(toast.error).toHaveBeenCalledWith('Invalid DSL kind')
})
@@ -180,7 +181,7 @@ describe('base', () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(errorResponse)
- await expect(base('/imports')).rejects.toBeInstanceOf(Response)
+ await expect(base('/imports')).rejects.toBeInstanceOf(ORPCError)
expect(toast.error).not.toHaveBeenCalled()
})
@@ -205,7 +206,7 @@ describe('base', () => {
try {
await expect(
base(`/apps/${appId}/workflows/draft/system-variables`),
- ).rejects.toBeInstanceOf(Response)
+ ).rejects.toBeInstanceOf(ORPCError)
expect(toast.error).not.toHaveBeenCalled()
} finally {
markAppDeletionFailed(appId)
@@ -232,7 +233,7 @@ describe('base', () => {
await expect(
base(`/apps/${appId}/workflows/draft/conversation-variables`),
- ).rejects.toBeInstanceOf(Response)
+ ).rejects.toBeInstanceOf(ORPCError)
expect(toast.error).not.toHaveBeenCalled()
})
@@ -255,7 +256,7 @@ describe('base', () => {
)
await expect(base(`/apps/${appId}/workflows/draft/variables`)).rejects.toBeInstanceOf(
- Response,
+ ORPCError,
)
expect(toast.error).toHaveBeenCalledWith('Visible error')
})
@@ -294,7 +295,7 @@ describe('base', () => {
)
try {
- await expect(base(path)).rejects.toBeInstanceOf(Response)
+ await expect(base(path)).rejects.toBeInstanceOf(ORPCError)
expect(toast.error).toHaveBeenCalledWith('Visible error')
} finally {
markAppDeletionFailed(appId)
diff --git a/web/service/fetch.ts b/web/service/fetch.ts
index c6dc9b0f519..ecad85e0677 100644
--- a/web/service/fetch.ts
+++ b/web/service/fetch.ts
@@ -1,7 +1,7 @@
import type { AfterResponseHook, BeforeRequestHook, Hooks } from 'ky'
import type { IOtherOptions } from './base'
import Cookies from 'js-cookie'
-import ky, { HTTPError } from 'ky'
+import ky from 'ky'
import {
API_PREFIX,
APP_VERSION,
@@ -14,6 +14,7 @@ import {
WEB_APP_SHARE_CODE_HEADER_NAME,
} from '@/config'
import { shouldSuppressAppDeletionErrorToast } from './app-deletion'
+import { httpErrorFromResponse, isHttpErrorStatus } from './http-error'
import { clearRequestErrorToasts, notifyRequestError } from './request-error-toast'
import { getWebAppPublicApiPath, resolveWebAppAddress } from './webapp-address'
import { getWebAppAccessToken, getWebAppPassport } from './webapp-auth'
@@ -44,50 +45,26 @@ const afterResponse204: AfterResponseHook = async ({ response }) => {
}
}
-export type ResponseError = {
- code: string
- message: string
- error?: string
- reason?: string
- status: number
-}
-
-const createResponseFromHTTPError = (error: HTTPError): Response => {
- const headers = new Headers(error.response.headers)
- headers.delete('content-length')
-
- let body: BodyInit | null = null
- if (typeof error.data === 'string') body = error.data
- else if (error.data !== undefined) body = JSON.stringify(error.data)
-
- if (body !== null && !headers.has('content-type')) headers.set('content-type', ContentType.json)
-
- return new Response(body, {
- status: error.response.status,
- statusText: error.response.statusText,
- headers,
- })
-}
-
const afterResponseErrorCode = (otherOptions: IOtherOptions): AfterResponseHook => {
return async ({ request, response }) => {
- if (!/^[23]\d{2}$/.test(String(response.status))) {
- let errorData: ResponseError | null = null
- try {
- const data: unknown = await response.clone().json()
- errorData = data as ResponseError
- } catch {}
+ if (isHttpErrorStatus(response.status)) {
+ const error = await httpErrorFromResponse(response)
+ const errorData = error.data
const shouldNotifyError =
+ response.status >= 400 &&
response.status !== 401 &&
errorData &&
!otherOptions.silent &&
!shouldSuppressAppDeletionErrorToast(request.url, response.status)
- const errorMessage = errorData?.message || errorData?.error
+ const errorMessage = [errorData?.message, errorData?.error].find(
+ (value): value is string => typeof value === 'string' && !!value.trim(),
+ )
if (shouldNotifyError && errorMessage) notifyRequestError(request, errorMessage)
if (response.status === 403 && errorData?.code === 'already_setup')
globalThis.location.href = `${globalThis.location.origin}/signin`
+ throw error
} else {
clearRequestErrorToasts(request)
}
@@ -112,6 +89,7 @@ const baseHooks: Hooks = {
const baseClient = ky.create({
hooks: baseHooks,
+ throwHttpErrors: isHttpErrorStatus,
timeout: TIME_OUT,
})
@@ -193,32 +171,26 @@ async function base<T>(
},
})
- let res: Response
- try {
- res = await client(request || fetchPathname, {
- ...init,
- headers,
- credentials: isMarketplaceAPI ? 'omit' : options.credentials || 'include',
- retry: {
- methods: [],
- },
- ...(bodyStringify && !fetchCompat ? { json: body } : { body: body as BodyInit }),
- searchParams: !fetchCompat ? params : undefined,
- fetch(resource: RequestInfo | URL, options?: RequestInit) {
- if (resource instanceof Request && options) {
- const mergedHeaders = new Headers(options.headers || {})
- resource.headers.forEach((value, key) => {
- mergedHeaders.append(key, value)
- })
- options.headers = mergedHeaders
- }
- return globalThis.fetch(resource, options)
- },
- })
- } catch (error) {
- if (error instanceof HTTPError) throw createResponseFromHTTPError(error)
- throw error
- }
+ const res = await client(request || fetchPathname, {
+ ...init,
+ headers,
+ credentials: isMarketplaceAPI ? 'omit' : options.credentials || 'include',
+ retry: {
+ methods: [],
+ },
+ ...(bodyStringify && !fetchCompat ? { json: body } : { body: body as BodyInit }),
+ searchParams: !fetchCompat ? params : undefined,
+ fetch(resource: RequestInfo | URL, options?: RequestInit) {
+ if (resource instanceof Request && options) {
+ const mergedHeaders = new Headers(options.headers || {})
+ resource.headers.forEach((value, key) => {
+ mergedHeaders.append(key, value)
+ })
+ options.headers = mergedHeaders
+ }
+ return globalThis.fetch(resource, options)
+ },
+ })
if (needAllResponseContent || fetchCompat) return res as T
const contentType = res.headers.get('content-type')
diff --git a/web/service/http-error.spec.ts b/web/service/http-error.spec.ts
new file mode 100644
index 00000000000..0d980b78348
--- /dev/null
+++ b/web/service/http-error.spec.ts
@@ -0,0 +1,276 @@
+import { ORPCError } from '@orpc/client'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { toast } from '@/app/notifications'
+// oxlint-disable-next-line no-restricted-imports -- Exercise the HTTP transport and auth recovery together.
+import { get, post, request, upload } from './base'
+import { consoleClient } from './console'
+
+const refresh = vi.hoisted(() => vi.fn())
+vi.mock('./refresh-token', () => ({ refreshAccessTokenOrReLogin: refresh }))
+vi.mock('@/app/notifications', () => ({ toast: { error: vi.fn() } }))
+
+beforeEach(() => {
+ window.history.replaceState({}, '', '/')
+ refresh.mockReset()
+})
+
+describe('upload HTTP failure contract', () => {
+ const createUpload = (status: number, response: unknown) => {
+ const xhr = new XMLHttpRequest()
+ vi.spyOn(xhr, 'open').mockImplementation(() => {})
+ vi.spyOn(xhr, 'setRequestHeader').mockImplementation(() => {})
+ vi.spyOn(xhr, 'getAllResponseHeaders').mockReturnValue('X-Request-Id: upload-123\r\n')
+ Object.defineProperties(xhr, {
+ readyState: { value: 1, configurable: true },
+ status: { value: status },
+ statusText: { value: '' },
+ response: { value: response },
+ })
+ vi.spyOn(xhr, 'send').mockImplementation(() => {
+ Object.defineProperty(xhr, 'readyState', { value: 4 })
+ xhr.dispatchEvent(new Event('readystatechange'))
+ })
+ return xhr
+ }
+
+ it.each([200, 201])('resolves successful HTTP %s uploads', async (status) => {
+ const response = { id: 'file-1' }
+ await expect(
+ upload({ xhr: createUpload(status, response), data: new FormData() }),
+ ).resolves.toEqual(response)
+ })
+
+ it('rejects HTTP failures with the same ORPCError as fetch requests', async () => {
+ const data = {
+ code: 'file_extension_blocked',
+ message: 'File type not allowed',
+ details: { request_id: 'upload-123' },
+ }
+ const error = await upload({ xhr: createUpload(400, data), data: new FormData() }).catch(
+ (error: unknown) => error,
+ )
+ expect(error).toBeInstanceOf(ORPCError)
+ expect(error).toMatchObject({
+ code: data.code,
+ message: data.message,
+ status: 400,
+ data,
+ })
+ if (!(error instanceof ORPCError)) throw new Error('Expected an upload HTTP failure')
+ expect(error.cause).toEqual({ headers: new Headers({ 'X-Request-Id': 'upload-123' }) })
+ })
+
+ it.each([
+ ['error', 'TypeError'],
+ ['abort', 'AbortError'],
+ ['timeout', 'TimeoutError'],
+ ])('keeps upload %s distinct from HTTP failures', async (event, name) => {
+ const xhr = createUpload(0, null)
+ vi.mocked(xhr.send).mockImplementation(() => {
+ Object.defineProperty(xhr, 'readyState', { value: 4 })
+ xhr.dispatchEvent(new Event('readystatechange'))
+ xhr.dispatchEvent(new Event(event))
+ })
+ await expect(upload({ xhr, data: new FormData() })).rejects.toMatchObject({ name })
+ })
+})
+
+describe('HTTP failure contract', () => {
+ it.each([400, 403, 404, 422, 429, 500, 503])(
+ 'exposes status %s as an Error with reusable metadata',
+ async (status) => {
+ const body = {
+ code: 'operation_failed',
+ message: 'Could not save',
+ status: 200,
+ reason: 'WORKSPACE_UNAVAILABLE',
+ hint: 'Try again later',
+ details: [{ loc: ['name'], msg: 'Required', type: 'missing' }],
+ }
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json(body, {
+ status,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Retry-After': '10',
+ 'X-Request-Id': 'request-123',
+ },
+ }),
+ )
+
+ const error = await post('/test-errors', { body: {} }, { silent: true }).catch(
+ (error: unknown) => error,
+ )
+
+ expect(error).toBeInstanceOf(Error)
+ expect(error).toBeInstanceOf(ORPCError)
+ if (!(error instanceof ORPCError)) throw new Error('Expected an HTTP failure')
+ expect(error).toMatchObject({
+ code: body.code,
+ message: body.message,
+ status,
+ data: body,
+ defined: false,
+ })
+ expect(error.cause).toEqual({
+ headers: new Headers({
+ 'Content-Type': 'application/json',
+ 'Retry-After': '10',
+ 'X-Request-Id': 'request-123',
+ }),
+ })
+ expect(String(error)).toBe('Error: Could not save')
+ expect(error.data).toEqual(body)
+ },
+ )
+
+ it.each(['', '<html>Bad gateway</html>', '{invalid', 'null', '[]'])(
+ 'handles a non-contract response body: %s',
+ async (body) => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(body, { status: 502, statusText: 'Bad Gateway' }),
+ )
+ await expect(get('/test-errors', {}, { silent: true })).rejects.toMatchObject({
+ defined: false,
+ message: 'Bad Gateway',
+ status: 502,
+ })
+ },
+ )
+
+ it('accepts the legacy error field and uses a status fallback for invalid messages', async () => {
+ const fetch = vi.spyOn(globalThis, 'fetch')
+ fetch.mockResolvedValueOnce(Response.json({ error: 'Upload rejected' }, { status: 413 }))
+ await expect(post('/test-errors', {}, { silent: true })).rejects.toMatchObject({
+ message: 'Upload rejected',
+ status: 413,
+ })
+ fetch.mockResolvedValueOnce(
+ Response.json({ message: { internal: 'invalid' } }, { status: 500 }),
+ )
+ await expect(get('/test-errors', {}, { silent: true })).rejects.toMatchObject({
+ message: 'HTTP 500',
+ status: 500,
+ })
+ })
+
+ it('keeps login failures as ORPCError instead of rejecting a plain object', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json({ code: 'invalid_credentials', message: 'Invalid password' }, { status: 401 }),
+ )
+ await expect(post('/login', {}, { silent: true })).rejects.toMatchObject({
+ defined: false,
+ code: 'invalid_credentials',
+ message: 'Invalid password',
+ status: 401,
+ })
+ expect(refresh).not.toHaveBeenCalled()
+ })
+
+ it('retries after token refresh and normalizes the retried HTTP failure', async () => {
+ const fetch = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(Response.json({ code: 'unauthorized' }, { status: 401 }))
+ .mockResolvedValueOnce(
+ Response.json({ code: 'forbidden', message: 'Access denied' }, { status: 403 }),
+ )
+ refresh.mockResolvedValue(undefined)
+ await expect(get('/test-errors', {}, { silent: true })).rejects.toMatchObject({
+ defined: false,
+ message: 'Access denied',
+ status: 403,
+ })
+ expect(refresh).toHaveBeenCalledOnce()
+ expect(fetch).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([429, 503])(
+ 'keeps the session when token refresh fails with transient HTTP %s',
+ async (status) => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json({ code: 'unauthorized' }, { status: 401 }),
+ )
+ const refreshError = new ORPCError('HTTP_ERROR', { status })
+ refresh.mockRejectedValue(refreshError)
+ const initialUrl = window.location.href
+
+ await expect(get('/test-errors', {}, { silent: true })).rejects.toBe(refreshError)
+ expect(refresh).toHaveBeenCalledOnce()
+ expect(window.location.href).toBe(initialUrl)
+ },
+ )
+
+ it('does not treat 3xx responses as HTTP failures', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 304 }))
+
+ await expect(
+ request<Response>('/test-errors', {}, { needAllResponseContent: true }),
+ ).resolves.toMatchObject({ status: 304 })
+ })
+
+ it('preserves network and abort errors without inventing HTTP status codes', async () => {
+ const fetch = vi.spyOn(globalThis, 'fetch')
+ for (const error of [
+ new TypeError('Failed to fetch'),
+ new DOMException('Cancelled', 'AbortError'),
+ ]) {
+ fetch.mockRejectedValueOnce(error)
+ const caught = await request('/test-errors', {}, { silent: true }).catch(
+ (error: unknown) => error,
+ )
+ expect(caught).toBeInstanceOf(Error)
+ expect(caught).not.toBeInstanceOf(ORPCError)
+ if (error.name === 'AbortError') expect(caught).toBe(error)
+ else expect(caught).toMatchObject({ name: 'NetworkError', cause: error })
+ }
+ })
+
+ it('preserves cancellation while reading a 401 body without starting authentication recovery', async () => {
+ const controller = new AbortController()
+ const abortError = new DOMException('Cancelled while reading the response', 'AbortError')
+ let resolveBodyRead: () => void
+ const bodyRead = new Promise<void>((resolve) => {
+ resolveBodyRead = resolve
+ })
+ const initialUrl = window.location.href
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const signal = (input as Request).signal
+ return new Response(
+ new ReadableStream(
+ {
+ start(body) {
+ signal.addEventListener('abort', () => body.error(signal.reason), { once: true })
+ },
+ pull() {
+ resolveBodyRead()
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ { status: 401 },
+ )
+ })
+
+ const pending = get('/test-errors', { signal: controller.signal }).catch(
+ (error: unknown) => error,
+ )
+ await bodyRead
+ controller.abort(abortError)
+
+ expect(await pending).toBe(abortError)
+ expect(refresh).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(window.location.href).toBe(initialUrl)
+ })
+
+ it('preserves ORPCError through the generated Console client', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json({ code: 'forbidden', message: 'Profile is read-only' }, { status: 403 }),
+ )
+ const error = await consoleClient.account.profile
+ .get({}, { context: { silent: true } })
+ .catch((error: unknown) => error)
+ expect(error).toBeInstanceOf(ORPCError)
+ expect(error).toMatchObject({ message: 'Profile is read-only', status: 403, code: 'forbidden' })
+ })
+})
diff --git a/web/service/http-error.ts b/web/service/http-error.ts
new file mode 100644
index 00000000000..544a0ad7bb8
--- /dev/null
+++ b/web/service/http-error.ts
@@ -0,0 +1,75 @@
+import { ORPCError } from '@orpc/client'
+
+export function getHttpErrorStatus(error: unknown): number | undefined {
+ return error instanceof ORPCError ? error.status : undefined
+}
+
+export function isUnauthorizedError(error: unknown): boolean {
+ return getHttpErrorStatus(error) === 401
+}
+
+export function isNotFoundError(error: unknown): boolean {
+ return getHttpErrorStatus(error) === 404
+}
+
+/** 3xx responses are not failures, and ORPCError rejects statuses in 200-399. */
+export function isHttpErrorStatus(status: number): boolean {
+ return status < 200 || status >= 400
+}
+
+/** Rate limits and server outages are worth retrying instead of treating as a final answer. */
+export function isTransientHttpError(error: unknown): boolean {
+ const status = getHttpErrorStatus(error)
+ return status === 408 || status === 429 || (status !== undefined && status >= 500)
+}
+
+const asRecord = (value: unknown): Record<string, unknown> | undefined =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined
+
+const nonEmptyString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim() ? value : undefined
+
+/** Decode the backend envelope without declaring it as a validated contract error. */
+export function createHttpError(
+ response: Pick<Response, 'status' | 'statusText' | 'headers'>,
+ body?: unknown,
+) {
+ const data = asRecord(body)
+ return new ORPCError(nonEmptyString(data?.code) ?? 'HTTP_ERROR', {
+ // The HTTP status is authoritative even when the response body disagrees.
+ status: response.status,
+ message:
+ nonEmptyString(data?.message) ??
+ nonEmptyString(data?.error) ??
+ nonEmptyString(response.statusText) ??
+ `HTTP ${response.status}`,
+ data,
+ cause: { headers: new Headers(response.headers) },
+ })
+}
+
+export function httpErrorFromXhr(xhr: XMLHttpRequest) {
+ const headers = new Headers()
+ for (const line of xhr
+ .getAllResponseHeaders()
+ .trim()
+ .split(/[\r\n]+/)) {
+ const separator = line.indexOf(':')
+ if (separator > 0) headers.append(line.slice(0, separator), line.slice(separator + 1).trim())
+ }
+ return createHttpError({ status: xhr.status, statusText: xhr.statusText, headers }, xhr.response)
+}
+
+export async function httpErrorFromResponse(response: Response) {
+ let body: unknown
+ try {
+ body = await response.clone().json()
+ } catch (error) {
+ // Empty, malformed JSON and proxy HTML errors still carry an HTTP status.
+ // Body read failures, including cancellation, must keep their original identity.
+ if (!(error instanceof SyntaxError)) throw error
+ }
+ return createHttpError(response, body)
+}
diff --git a/web/service/knowledge/use-dataset.spec.ts b/web/service/knowledge/use-dataset.spec.ts
index 161627934f0..ca472887f0d 100644
--- a/web/service/knowledge/use-dataset.spec.ts
+++ b/web/service/knowledge/use-dataset.spec.ts
@@ -1,4 +1,5 @@
import { useQuery } from '@tanstack/react-query'
+import { createHttpError } from '@/service/http-error'
import { get } from '../base'
import { useDatasetDetail, useDatasetRelatedApps } from './use-dataset'
@@ -46,8 +47,8 @@ describe('knowledge dataset hooks', () => {
const retry = getRetryFn()
// Assert
- expect(retry(0, new Response(null, { status: 403 }))).toBe(false)
- expect(retry(0, new Response(null, { status: 404 }))).toBe(false)
+ expect(retry(0, createHttpError(new Response(null, { status: 403 })))).toBe(false)
+ expect(retry(0, createHttpError(new Response(null, { status: 404 })))).toBe(false)
})
it('should retry other dataset detail errors fewer than three times', () => {
diff --git a/web/service/knowledge/use-dataset.ts b/web/service/knowledge/use-dataset.ts
index 2a4e129cf18..1785beffa63 100644
--- a/web/service/knowledge/use-dataset.ts
+++ b/web/service/knowledge/use-dataset.ts
@@ -12,6 +12,7 @@ import type {
ProcessRuleResponse,
RelatedAppResponse,
} from '@/models/datasets'
+import { ORPCError } from '@orpc/client'
import { keepPreviousData, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'
import qs from 'qs'
import { get, post } from '../base'
@@ -103,7 +104,7 @@ export const useDatasetDetail = (datasetId: string) => {
queryFn: () => get<DataSet>(`/datasets/${datasetId}`),
enabled: !!datasetId,
retry: (failureCount, error) => {
- if (error instanceof Response && [403, 404].includes(error.status)) return false
+ if (error instanceof ORPCError && [403, 404].includes(error.status)) return false
return failureCount < 3
},
diff --git a/web/service/refresh-token.spec.ts b/web/service/refresh-token.spec.ts
new file mode 100644
index 00000000000..20303f6c302
--- /dev/null
+++ b/web/service/refresh-token.spec.ts
@@ -0,0 +1,34 @@
+import { ORPCError } from '@orpc/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { refreshAccessTokenOrReLogin } from './refresh-token'
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ localStorage.clear()
+})
+
+afterEach(() => {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+})
+
+describe('token refresh HTTP failures', () => {
+ it.each([400, 401, 503])(
+ 'rejects HTTP %s as ORPCError and releases the refresh lock',
+ async (status) => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json({ code: 'refresh_failed', message: 'Refresh failed' }, { status }),
+ )
+ const error = await refreshAccessTokenOrReLogin(1000).catch((error: unknown) => error)
+ expect(error).toBeInstanceOf(ORPCError)
+ expect(error).toMatchObject({ code: 'refresh_failed', message: 'Refresh failed', status })
+ expect(localStorage.getItem('is_other_tab_refreshing')).toBeNull()
+ },
+ )
+
+ it('resolves a successful refresh', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ result: 'success' }))
+ await expect(refreshAccessTokenOrReLogin(1000)).resolves.toBeUndefined()
+ expect(localStorage.getItem('is_other_tab_refreshing')).toBeNull()
+ })
+})
diff --git a/web/service/refresh-token.ts b/web/service/refresh-token.ts
index 80d75ec5368..fdd43bf102b 100644
--- a/web/service/refresh-token.ts
+++ b/web/service/refresh-token.ts
@@ -1,6 +1,7 @@
import { API_PREFIX } from '@/config'
import { fetchWithRetry } from '@/utils'
import { isClient } from '@/utils/client'
+import { httpErrorFromResponse, isHttpErrorStatus } from './http-error'
const LOCAL_STORAGE_KEY = 'is_other_tab_refreshing'
@@ -60,7 +61,7 @@ async function getNewAccessToken(timeout: number): Promise<void> {
if (error) {
return Promise.reject(error)
} else {
- if (ret.status === 401) return Promise.reject(ret)
+ if (isHttpErrorStatus(ret.status)) throw await httpErrorFromResponse(ret)
}
}
} catch (error) {
diff --git a/web/service/share.spec.ts b/web/service/share.spec.ts
index cb0e5b32e74..4b4f6395314 100644
--- a/web/service/share.spec.ts
+++ b/web/service/share.spec.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createHttpError } from './http-error'
const getMock = vi.hoisted(() => vi.fn())
@@ -75,7 +76,7 @@ describe('fetchAccessToken', () => {
it('starts a new environment passport request after a failure', async () => {
window.history.replaceState({}, '', '/environment/workflow/environment-app')
- const error = new Response(null, { status: 401 })
+ const error = createHttpError(new Response(null, { status: 401 }))
getMock.mockRejectedValueOnce(error).mockResolvedValueOnce({ access_token: 'passport' })
await expect(fetchAccessToken({ appCode: 'environment-app' })).rejects.toBe(error)
diff --git a/web/service/use-share.spec.tsx b/web/service/use-share.spec.tsx
index 366c4595c6a..604cf7938a4 100644
--- a/web/service/use-share.spec.tsx
+++ b/web/service/use-share.spec.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import type { AppConversationData, ConversationItem } from '@/models/share'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
+import { httpErrorFromResponse } from '@/service/http-error'
import {
AppSourceType,
fetchChatList,
@@ -218,7 +219,8 @@ describe('useShareChatList', () => {
const response = new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {
status: 404,
})
- mockFetchChatList.mockRejectedValue(response)
+ const apiError = await httpErrorFromResponse(response)
+ mockFetchChatList.mockRejectedValue(apiError)
const { result } = renderShareHook(() => useShareChatList(params))
@@ -236,12 +238,13 @@ describe('useShareChatList', () => {
appSourceType: AppSourceType.webApp,
}
const response = new Response(JSON.stringify({ reason: 'OTHER_ERROR' }), { status: 404 })
- mockFetchChatList.mockRejectedValue(response)
+ const apiError = await httpErrorFromResponse(response)
+ mockFetchChatList.mockRejectedValue(apiError)
const { result } = renderShareHook(() => useShareChatList(params))
await waitFor(() => {
- expect(result.current.error).toBe(response)
+ expect(result.current.error).toBe(apiError)
})
expect(mockFetchChatList).toHaveBeenCalledTimes(1)
})
@@ -255,12 +258,13 @@ describe('useShareChatList', () => {
const response = new Response(JSON.stringify({ reason: 'APPDEPLOY_CONVERSATION_NOT_FOUND' }), {
status: 404,
})
- mockFetchChatList.mockRejectedValue(response)
+ const apiError = await httpErrorFromResponse(response)
+ mockFetchChatList.mockRejectedValue(apiError)
const { result } = renderShareHook(() => useShareChatList(params))
await waitFor(() => {
- expect(result.current.error).toBe(response)
+ expect(result.current.error).toBe(apiError)
})
expect(mockFetchChatList).toHaveBeenCalledTimes(1)
})
diff --git a/web/service/use-share.ts b/web/service/use-share.ts
index 7f814230ac7..07f7d1ce24c 100644
--- a/web/service/use-share.ts
+++ b/web/service/use-share.ts
@@ -1,6 +1,7 @@
import type { WebAppAddress } from './webapp-address'
import type { FormData as HumanInputFormData } from '@/app/(humanInputLayout)/form/[token]/form'
import type { AppConversationData, ConversationItem } from '@/models/share'
+import { ORPCError } from '@orpc/client'
import { useMutation, useQuery } from '@tanstack/react-query'
import {
AppSourceType,
@@ -149,9 +150,8 @@ export const useShareChatList = (params: ShareChatListParams, options: ShareQuer
try {
return await fetchChatList(params.conversationId, params.appSourceType, params.appId)
} catch (error) {
- if (address?.kind === 'environment' && error instanceof Response && error.status === 404) {
- const data = (await error.clone().json()) as { reason?: string }
- if (data.reason === 'APPDEPLOY_CONVERSATION_NOT_FOUND')
+ if (address?.kind === 'environment' && error instanceof ORPCError && error.status === 404) {
+ if (error.data?.reason === 'APPDEPLOY_CONVERSATION_NOT_FOUND')
throw new EnvironmentConversationNotFoundError()
}
throw error
@@ -191,34 +191,11 @@ export const useInvalidateShareConversations = () => {
return useInvalid(shareQueryKeys.conversations)
}
-export class HumanInputFormError extends Error {
- code: string
- status: number
-
- constructor(code: string, message: string, status: number) {
- super(message)
- this.name = 'HumanInputFormError'
- this.code = code
- this.status = status
- }
-}
-
export const useGetHumanInputForm = (token: string, options: ShareQueryOptions = {}) => {
const { enabled = true, refetchOnReconnect, refetchOnWindowFocus } = options
- return useQuery<HumanInputFormData, HumanInputFormError>({
+ return useQuery<HumanInputFormData>({
queryKey: shareQueryKeys.humanInputForm(token),
- queryFn: async () => {
- try {
- return await getHumanInputForm(token)
- } catch (error) {
- const response = error as Response
- if (response.status && response.json) {
- const errorData = (await response.json()) as { code: string; message: string }
- throw new HumanInputFormError(errorData.code, errorData.message, response.status)
- }
- throw error
- }
- },
+ queryFn: () => getHumanInputForm(token),
enabled: enabled && !!token,
refetchOnReconnect,
refetchOnWindowFocus,
diff --git a/web/service/use-snippet-workflows.ts b/web/service/use-snippet-workflows.ts
index fa769a110e3..beea1c238d8 100644
--- a/web/service/use-snippet-workflows.ts
+++ b/web/service/use-snippet-workflows.ts
@@ -1,10 +1,7 @@
import type { PublishSnippetWorkflowResponse, SnippetWorkflow } from '@/types/snippet'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { consoleClient, consoleQuery } from '@/service/console'
-
-const isNotFoundError = (error: unknown) => {
- return !!error && typeof error === 'object' && 'status' in error && error.status === 404
-}
+import { isNotFoundError } from '@/service/http-error'
export const fetchSnippetDraftWorkflow = async (snippetId: string) => {
try {
diff --git a/web/utils/error-message.ts b/web/utils/error-message.ts
new file mode 100644
index 00000000000..58868f792d1
--- /dev/null
+++ b/web/utils/error-message.ts
@@ -0,0 +1,3 @@
+export function getErrorMessage(error: unknown): string | undefined {
+ return error instanceof Error ? error.message || undefined : undefined
+}
diff --git a/web/utils/error-parser.ts b/web/utils/error-parser.ts
index b10617a3807..4fc4222681f 100644
--- a/web/utils/error-parser.ts
+++ b/web/utils/error-parser.ts
@@ -6,25 +6,11 @@
* Input: { message: "req_id: xxx PluginInvokeError: {\"message\":\"Bad credentials\"}" }
* Output: "Bad credentials"
*
- * @param error - Error object (can be Response object or error with message property)
- * @returns Promise<string> or string - Parsed error message
+ * @param error - Error object (an Error or object with a message property)
+ * @returns Parsed error message
*/
-export const parsePluginErrorMessage = async (error: any): Promise<string> => {
- let rawMessage = ''
-
- // Handle Response object from fetch/ky
- if (error instanceof Response) {
- try {
- const body = await error.clone().json()
- rawMessage = body?.message || error.statusText || 'Unknown error'
- } catch {
- rawMessage = error.statusText || 'Unknown error'
- }
- } else {
- rawMessage = error?.message || error?.toString() || 'Unknown error'
- }
-
- console.log('rawMessage', rawMessage)
+export const parsePluginErrorMessage = (error: any): string => {
+ const rawMessage = error?.message || error?.toString() || 'Unknown error'
// Try to extract nested JSON from PluginInvokeError
// Use greedy match .+ to capture the complete JSON object with nested braces