Skip to content

Commit 9d458c3

Browse files
committed
feat: improve error message display
1 parent 42e547e commit 9d458c3

File tree

4 files changed

+47
-19
lines changed

4 files changed

+47
-19
lines changed

backend/apps/chat/task/llm.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from langchain_community.utilities import SQLDatabase
1616
from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, BaseMessageChunk
1717
from sqlalchemy import select
18-
from sqlalchemy.exc import DBAPIError
1918
from sqlalchemy.orm import sessionmaker
2019
from sqlmodel import create_engine, Session
2120

@@ -30,13 +29,13 @@
3029
from apps.datasource.crud.datasource import get_table_schema
3130
from apps.datasource.crud.permission import get_row_permission_filters, is_normal_user
3231
from apps.datasource.models.datasource import CoreDatasource
33-
from apps.db.db import exec_sql, get_version
32+
from apps.db.db import exec_sql, get_version, check_connection
3433
from apps.system.crud.assistant import AssistantOutDs, AssistantOutDsFactory, get_assistant_ds
3534
from apps.system.schemas.system_schema import AssistantOutDsSchema
3635
from apps.terminology.curd.terminology import get_terminology_template
3736
from common.core.config import settings
3837
from common.core.deps import CurrentAssistant, CurrentUser
39-
from common.error import SingleMessageError
38+
from common.error import SingleMessageError, SQLBotDBError, ParseSQLResultError, SQLBotDBConnectionError
4039
from common.utils.utils import SQLBotLogUtil, extract_nested_json, prepare_for_orjson
4140

4241
warnings.filterwarnings("ignore")
@@ -868,7 +867,14 @@ def execute_sql(self, sql: str):
868867
Query results
869868
"""
870869
SQLBotLogUtil.info(f"Executing SQL on ds_id {self.ds.id}: {sql}")
871-
return exec_sql(self.ds, sql)
870+
try:
871+
return exec_sql(self.ds, sql)
872+
except Exception as e:
873+
if isinstance(e, ParseSQLResultError):
874+
raise e
875+
else:
876+
err = traceback.format_exc(limit=1, chain=True)
877+
raise SQLBotDBError(err)
872878

873879
def pop_chunk(self):
874880
try:
@@ -940,6 +946,12 @@ def run_task(self, in_chat: bool = True):
940946
ds=self.ds)
941947
else:
942948
self.validate_history_ds()
949+
950+
# check connection
951+
connected = check_connection(ds=self.ds, trans=None)
952+
if not connected:
953+
raise SQLBotDBConnectionError('Connect DB failed')
954+
943955
# generate sql
944956
sql_res = self.generate_sql()
945957
full_sql_text = ''
@@ -1059,13 +1071,12 @@ def run_task(self, in_chat: bool = True):
10591071
error_msg: str
10601072
if isinstance(e, SingleMessageError):
10611073
error_msg = str(e)
1062-
elif isinstance(e, ConnectionError):
1074+
elif isinstance(e, SQLBotDBConnectionError):
10631075
error_msg = orjson.dumps(
1064-
{'message': str(e), 'traceback': traceback.format_exc(limit=1),
1065-
'type': 'db-connection-err'}).decode()
1066-
elif isinstance(e, DBAPIError):
1076+
{'message': str(e), 'type': 'db-connection-err'}).decode()
1077+
elif isinstance(e, SQLBotDBError):
10671078
error_msg = orjson.dumps(
1068-
{'message': str(e), 'traceback': traceback.format_exc(limit=1), 'type': 'exec-sql-err'}).decode()
1079+
{'message': 'Execute SQL Failed', 'traceback': str(e), 'type': 'exec-sql-err'}).decode()
10691080
else:
10701081
error_msg = orjson.dumps({'message': str(e), 'traceback': traceback.format_exc(limit=1)}).decode()
10711082
self.save_error(message=error_msg)

backend/apps/db/db.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
import platform
44
import urllib.parse
55
from decimal import Decimal
6+
from typing import Optional
67

78
from apps.db.db_sql import get_table_sql, get_field_sql, get_version_sql
9+
from common.error import ParseSQLResultError
810

911
if platform.system() != "Darwin":
1012
import dmPython
@@ -100,7 +102,7 @@ def get_session(ds: CoreDatasource | AssistantOutDsSchema):
100102
return session
101103

102104

103-
def check_connection(trans: Trans, ds: CoreDatasource, is_raise: bool = False):
105+
def check_connection(trans: Optional[Trans], ds: CoreDatasource, is_raise: bool = False):
104106
db = DB.get_db(ds.type)
105107
if db.connect_type == ConnectType.sqlalchemy:
106108
conn = get_engine(ds, 10)
@@ -209,7 +211,8 @@ def get_schema(ds: CoreDatasource):
209211
if ds.type == "sqlServer":
210212
sql = f"""select name from sys.schemas"""
211213
elif ds.type == "pg" or ds.type == "excel":
212-
sql = """SELECT nspname FROM pg_namespace"""
214+
sql = """SELECT nspname
215+
FROM pg_namespace"""
213216
elif ds.type == "oracle":
214217
sql = f"""select * from all_users"""
215218
with session.execute(text(sql)) as result:
@@ -325,7 +328,7 @@ def exec_sql(ds: CoreDatasource | AssistantOutDsSchema, sql: str, origin_column=
325328
return {"fields": columns, "data": result_list,
326329
"sql": bytes.decode(base64.b64encode(bytes(sql, 'utf-8')))}
327330
except Exception as ex:
328-
raise ex
331+
raise ParseSQLResultError(str(ex))
329332
else:
330333
conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration)))
331334
if ds.type == 'dm':
@@ -345,7 +348,7 @@ def exec_sql(ds: CoreDatasource | AssistantOutDsSchema, sql: str, origin_column=
345348
return {"fields": columns, "data": result_list,
346349
"sql": bytes.decode(base64.b64encode(bytes(sql, 'utf-8')))}
347350
except Exception as ex:
348-
raise ex
351+
raise ParseSQLResultError(str(ex))
349352
elif ds.type == 'doris':
350353
with pymysql.connect(user=conf.username, passwd=conf.password, host=conf.host,
351354
port=conf.port, db=conf.database, connect_timeout=conf.timeout,
@@ -364,7 +367,7 @@ def exec_sql(ds: CoreDatasource | AssistantOutDsSchema, sql: str, origin_column=
364367
return {"fields": columns, "data": result_list,
365368
"sql": bytes.decode(base64.b64encode(bytes(sql, 'utf-8')))}
366369
except Exception as ex:
367-
raise ex
370+
raise ParseSQLResultError(str(ex))
368371
elif ds.type == 'redshift':
369372
with redshift_connector.connect(host=conf.host, port=conf.port, database=conf.database, user=conf.username,
370373
password=conf.password,
@@ -383,4 +386,4 @@ def exec_sql(ds: CoreDatasource | AssistantOutDsSchema, sql: str, origin_column=
383386
return {"fields": columns, "data": result_list,
384387
"sql": bytes.decode(base64.b64encode(bytes(sql, 'utf-8')))}
385388
except Exception as ex:
386-
raise ex
389+
raise ParseSQLResultError(str(ex))

backend/common/error.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,16 @@ def __init__(self, message):
44
self.message = message
55

66
def __str__(self):
7-
return self.message
7+
return self.message
8+
9+
10+
class SQLBotDBConnectionError(Exception):
11+
pass
12+
13+
14+
class SQLBotDBError(Exception):
15+
pass
16+
17+
18+
class ParseSQLResultError(Exception):
19+
pass

frontend/src/views/chat/ErrorInfo.vue

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const showBlock = computed(() => {
1717
})
1818
1919
const errorMessage = computed(() => {
20-
const obj = { message: props.error, showMore: false, traceback: '', type: '' }
20+
const obj = { message: props.error, showMore: false, traceback: '', type: undefined }
2121
if (showBlock.value && props.error?.trim().startsWith('{') && props.error?.trim().endsWith('}')) {
2222
try {
2323
const json = JSON.parse(props.error?.trim())
@@ -44,7 +44,7 @@ function showTraceBack() {
4444
<template>
4545
<div v-if="showBlock">
4646
<div
47-
v-if="!errorMessage.showMore"
47+
v-if="!errorMessage.showMore && errorMessage.type == undefined"
4848
v-dompurify-html="errorMessage.message"
4949
class="error-container"
5050
></div>
@@ -58,7 +58,9 @@ function showTraceBack() {
5858
<template v-else>
5959
{{ t('chat.error') }}
6060
</template>
61-
<el-button text @click="showTraceBack">{{ t('chat.show_error_detail') }}</el-button>
61+
<el-button v-if="errorMessage.showMore" text @click="showTraceBack">
62+
{{ t('chat.show_error_detail') }}
63+
</el-button>
6264
</div>
6365

6466
<el-drawer

0 commit comments

Comments
 (0)