diff --git a/apps/common/exception/handle_exception.py b/apps/common/exception/handle_exception.py index 50fce4aa7..282862eb2 100644 --- a/apps/common/exception/handle_exception.py +++ b/apps/common/exception/handle_exception.py @@ -10,7 +10,6 @@ import logging import traceback from rest_framework.exceptions import ValidationError, ErrorDetail, APIException -from rest_framework.utils.serializer_helpers import ReturnDict from rest_framework.views import exception_handler from common import result @@ -60,28 +59,18 @@ def validation_error_to_result(exc: ValidationError): def find_err_detail(exc_detail): - if isinstance(exc_detail, ErrorDetail): + if isinstance(exc_detail, (ErrorDetail, str)): return exc_detail if isinstance(exc_detail, dict): - keys = exc_detail.keys() - for key in keys: - _label = get_label(key, exc_detail) - _value = exc_detail[key] - if isinstance(_value, list): - for v in _value: - r = find_err_detail(ReturnDict({key: v}, serializer=exc_detail.serializer)) - if r is not None: - return r - if isinstance(_value, ErrorDetail): - return f"{_label}:{find_err_detail(_value)}" - if isinstance(_value, dict) and len(_value.keys()) > 0: - try: - return find_err_detail(ReturnDict(_value, serializer=exc_detail.serializer.fields[key])) - except Exception as e: - return _value - if isinstance(exc_detail, list): + for key, value in exc_detail.items(): + detail = find_err_detail(value) + if detail is not None: + if key == 'non_field_errors': + return detail + return f'{get_label(key, exc_detail)}:{detail}' + if isinstance(exc_detail, (list, tuple)): for v in exc_detail: - r = find_err_detail(ReturnDict(v, serializer=exc_detail.serializer.child)) + r = find_err_detail(v) if r is not None: return r diff --git a/apps/common/exception/test_handle_exception.py b/apps/common/exception/test_handle_exception.py new file mode 100644 index 000000000..9ff4f3c9e --- /dev/null +++ b/apps/common/exception/test_handle_exception.py @@ -0,0 +1,18 @@ +import json +from django.test import SimpleTestCase +from rest_framework.exceptions import ValidationError +from common.exception.handle_exception import validation_error_to_result + + +class ValidationMessageTests(SimpleTestCase): + def test_plain_list_error_is_readable(self): + response = validation_error_to_result(ValidationError('最多可保存 10 张导图,请先删除不需要的导图')) + self.assertEqual(json.loads(response.content)['message'], '最多可保存 10 张导图,请先删除不需要的导图') + + def test_nested_error_retains_field_context(self): + response = validation_error_to_result(ValidationError({'document': {'name': ['不能为空']}})) + self.assertEqual(json.loads(response.content)['message'], 'document:name:不能为空') + + def test_non_field_error_has_no_internal_key(self): + response = validation_error_to_result(ValidationError({'non_field_errors': ['内容无效']})) + self.assertEqual(json.loads(response.content)['message'], '内容无效') diff --git a/apps/system_manage/ai_hub.py b/apps/system_manage/ai_hub.py index b6035da39..d7b7d0b5a 100644 --- a/apps/system_manage/ai_hub.py +++ b/apps/system_manage/ai_hub.py @@ -438,7 +438,7 @@ def submit(workspace, user, data, upload=None, service=None, request=None): User.objects.select_for_update().get(pk=user.id) maximum = limit() if AIArtifact.objects.filter(workspace_id=workspace, owner_id=user.id).count() >= maximum: - raise ValidationError(f'已达到导图保存上限({maximum}条),请删除后再保存') + raise ValidationError(f'最多可保存 {maximum} 张导图,请先删除不需要的导图') layout = spec.get('layout', 'tree') if layout not in ('tree', 'radial', 'horizontal', 'vertical'): raise ValidationError('布局无效') @@ -485,7 +485,7 @@ def artifact_save(workspace, user, data, obj=None): User.objects.select_for_update().get(pk=user.id) maximum = limit() if AIArtifact.objects.filter(workspace_id=workspace, owner_id=user.id).count() >= maximum: - raise ValidationError(f'已达到导图保存上限({maximum}条),请删除后再保存') + raise ValidationError(f'最多可保存 {maximum} 张导图,请先删除不需要的导图') task = one('tasks', data['task_id'], workspace, user, lock=True) if data.get('task_id') else None if task and task.status != 'SUCCESS': raise ValidationError('任务尚未成功') diff --git a/apps/system_manage/test_my_mindmaps.py b/apps/system_manage/test_my_mindmaps.py index fdc54c87b..a1f0e6800 100644 --- a/apps/system_manage/test_my_mindmaps.py +++ b/apps/system_manage/test_my_mindmaps.py @@ -166,7 +166,9 @@ class MyMindmapsChecks(TestCase): with self.assertRaises(ValidationError): artifact_settings.save(self.admin, {'limit': True}) data = {'name': 'new', 'markdown': '# source', 'layout': 'tree'} - self.assertNotEqual(self.api('post', self.user, data)['code'], 200) + limited = self.api('post', self.user, data) + self.assertNotEqual(limited['code'], 200) + self.assertEqual(limited['message'], '最多可保存 2 张导图,请先删除不需要的导图') self.assertEqual(self.api('post', self.other, data)['code'], 200) self.assertEqual(self.api('post', self.user, data, workspace='other')['code'], 200) data.update(revision=1, summary_state={'source_markdown': '# source', 'smart_markdown': '# summary', 'mode': 'source'}) diff --git a/ui/src/api/ai-hub.ts b/ui/src/api/ai-hub.ts index 768d9b8b7..1745c56c8 100644 --- a/ui/src/api/ai-hub.ts +++ b/ui/src/api/ai-hub.ts @@ -4,8 +4,10 @@ import useStore from '@/stores' export const hubBase = () => `/workspace/${useStore().user.getWorkspaceId()}/ai_hub` export const hubGet = (kind: string, id?: string) => get(`${hubBase()}/${kind}${id ? '/' + id : ''}`) -export const hubPost = (kind: string, data: any, id?: string) => - post(`${hubBase()}/${kind}${id ? '/' + id : ''}`, data) +export const hubPost = (kind: string, data: any, id?: string, silentError = false) => + silentError + ? request({ url: `${hubBase()}/${kind}${id ? '/' + id : ''}`, method: 'post', data, silentError: true } as any).then((response) => response.data) + : post(`${hubBase()}/${kind}${id ? '/' + id : ''}`, data) export const hubDelete = (kind: string, id: string) => request({ url: `${hubBase()}/${kind}/${id}`, method: 'delete' }) export async function hubBinary(kind: 'assets' | 'exports' | 'document_export', id?: string, data?: any) { diff --git a/ui/src/request/index.ts b/ui/src/request/index.ts index 35daf47df..ba5864e48 100644 --- a/ui/src/request/index.ts +++ b/ui/src/request/index.ts @@ -52,7 +52,7 @@ instance.interceptors.response.use( !response.config.url.includes('/valid') && !response.config.url.includes('/tool/debug') ) { - MsgError(response.data.message) + if (!(response.config as any).silentError) MsgError(response.data.message) return Promise.reject(response.data) } } @@ -60,7 +60,7 @@ instance.interceptors.response.use( return response }, (err: any) => { - if (err.code === 'ECONNABORTED') { + if (err.code === 'ECONNABORTED' && !err.config?.silentError) { MsgError(err.message) console.error(err) } @@ -78,7 +78,7 @@ instance.interceptors.response.use( } } - if (err.response?.status === 403 && !err.response.config.url.includes('chat/open')) { + if (err.response?.status === 403 && !err.config?.silentError && !err.response.config.url.includes('chat/open')) { MsgError( err.response.data && err.response.data.message ? err.response.data.message diff --git a/ui/src/views/mindmap/workbench/api/document.ts b/ui/src/views/mindmap/workbench/api/document.ts index 6e5e824b4..45d6f4532 100644 --- a/ui/src/views/mindmap/workbench/api/document.ts +++ b/ui/src/views/mindmap/workbench/api/document.ts @@ -145,6 +145,7 @@ export const documentApi = { { name: file.name.slice(0, 128), nodes: [node, { type: 'render' }], workbench_artifact: {} }, undefined, file, + true, ) ids.set(taskId, task.id) onCreated?.(task) diff --git a/ui/src/views/mindmap/workbench/api/hub.ts b/ui/src/views/mindmap/workbench/api/hub.ts index f0e3e257d..d0aea680b 100644 --- a/ui/src/views/mindmap/workbench/api/hub.ts +++ b/ui/src/views/mindmap/workbench/api/hub.ts @@ -3,14 +3,14 @@ import { useRoute } from 'vue-router' import { ElMessage } from 'element-plus' import { hubGet, hubPost, hubBinary } from '@/api/ai-hub' -export async function hubCall(kind: string, method = 'get', data?: any, id?: string, file?: File): Promise { +export async function hubCall(kind: string, method = 'get', data?: any, id?: string, file?: File, silentError = false): Promise { if (kind === 'assets' || kind === 'exports' || kind === 'document_export') return hubBinary(kind, id, data) if (file) { const form = new FormData() form.append('data', JSON.stringify(data)); form.append('file', file) data = form } - const response = method === 'get' ? await hubGet(kind, id) : await hubPost(kind, data, id) + const response = method === 'get' ? await hubGet(kind, id) : await hubPost(kind, data, id, silentError) return response.data } diff --git a/ui/src/views/mindmap/workbench/composables/useDocumentProcessor.ts b/ui/src/views/mindmap/workbench/composables/useDocumentProcessor.ts index ec5bc70d0..7dfb64c7e 100644 --- a/ui/src/views/mindmap/workbench/composables/useDocumentProcessor.ts +++ b/ui/src/views/mindmap/workbench/composables/useDocumentProcessor.ts @@ -404,7 +404,7 @@ export function useDocumentProcessor() { } catch (err: any) { if (generation !== processGeneration) return - error.value = err.message || '转换失败' + error.value = err.response?.data?.message || err.message || '转换失败' } finally { if (generation === processGeneration) { stopProgressPolling() diff --git a/ui/src/views/mindmap/workbench/views/DocumentProcessor.vue b/ui/src/views/mindmap/workbench/views/DocumentProcessor.vue index 3a5c71254..26c8a5da1 100644 --- a/ui/src/views/mindmap/workbench/views/DocumentProcessor.vue +++ b/ui/src/views/mindmap/workbench/views/DocumentProcessor.vue @@ -1117,7 +1117,7 @@ async function saveArtifact(silent = false) { summary_state: { source_markdown: manualMarkdownContent.value, smart_markdown: smartMarkdownContent.value, mode: sourceContentMode.value }, heading_structure: activeHeadingStructure.value, layout: graphLayout.value - }, current?.id) + }, current?.id, undefined, true) openedArtifact.value = saved rememberArtifact(saved.id) originalRecognized.value = saved.original || '' @@ -1125,7 +1125,7 @@ async function saveArtifact(silent = false) { results.value = { markdown: source, source, original: saved.original, headingStructure: sourceContentMode.value === 'source' ? saved.heading_structure : undefined, headingMarkdown: source, mindmap: buildMindmapMarkdown(saved.markdown), taskId: saved.task_id || undefined } await router.replace({path: '/mindmap', query: {...router.currentRoute.value.query, artifact: saved.id}}) if (!silent) ElMessage.success('已保存') - } catch (e: any) { ElMessage.error(e.message || '保存失败') } + } catch (e: any) { ElMessage.error(e.response?.data?.message || e.message || '保存失败') } finally { savingArtifact.value = false } }