fix(mindmap): surface backend validation messages in the workbench

find_err_detail relied on ReturnDict.serializer, so plain string and list
errors lost their message and nested ones could raise. Walk dicts and
lists directly instead, and keep the internal non_field_errors key out of
user-facing text.

The axios interceptor toasted every failure before the page could handle
it, so saving over the mindmap limit showed two messages and the workbench
fell back to a generic one. Add an opt-in silentError flag and let the
workbench render the server message itself.
v3.2-refact
panyy 2026-11-12 17:54:06 +08:00
parent 79fa2cf4a2
commit b23569e0b8
10 changed files with 45 additions and 33 deletions

View File

@ -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

View File

@ -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'], '内容无效')

View File

@ -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('任务尚未成功')

View File

@ -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'})

View File

@ -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) {

View File

@ -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

View File

@ -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)

View File

@ -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<any> {
export async function hubCall(kind: string, method = 'get', data?: any, id?: string, file?: File, silentError = false): Promise<any> {
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
}

View File

@ -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()

View File

@ -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 }
}