Skip to content

Commit

Permalink
feat: 新版api错误信息展示 --Story=119271711 (TencentBlueKing#2603)
Browse files Browse the repository at this point in the history
# Reviewed, transaction id: 15962
  • Loading branch information
liangling0628 authored Aug 27, 2024
1 parent ee84255 commit 288a8b5
Show file tree
Hide file tree
Showing 11 changed files with 175 additions and 77 deletions.
2 changes: 1 addition & 1 deletion bkmonitor/webpack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"clean:mobile": "rimraf weixin/*",
"clean:pc": "rimraf ../static/monitor/*",
"clean-dll": "rimraf ../static/monitor/dll/*",
"analyze": "npm run clean && bkmonitor-cli build -a",
"analyze": "npm run clean && bkmonitor-cli build -apm -a",
"analyze:mobile": "npm run clean && bkmonitor-cli build -m -a",
"analyze:fta": "npm run clean && bkmonitor-cli build -f -a",
"replace": "cross-env execMode=move node ./webpack/exec-shell.js",
Expand Down
2 changes: 1 addition & 1 deletion bkmonitor/webpack/src/apm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import 'monitor-common/polyfill';
import i18n from './i18n/i18n';
import Vue from 'vue';

import './common/import-magicbox-ui';
import 'monitor-pc/common/import-magicbox-ui';
import 'monitor-static/svg-icons';
import 'monitor-ui/directive/index';

Expand Down
2 changes: 1 addition & 1 deletion bkmonitor/webpack/src/fta-solutions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import 'monitor-common/polyfill';
import i18n from './i18n/i18n';
import Vue from 'vue';

import './common/import-magicbox-ui';
import 'monitor-pc/common/import-magicbox-ui';
import 'monitor-ui/directive/index';

import Api from 'monitor-api/api';
Expand Down
66 changes: 37 additions & 29 deletions bkmonitor/webpack/src/monitor-api/axios/axios.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ import { authorityStore, bkMessage, makeMessage } from '../utils/index';
const noMessageCode = [3314001, 3310003];
const errorHandle = (response, config) => {
const traceparent = config?.headers?.traceparent;
const resMessage = makeMessage(response.data.message || '请求出错了!', traceparent, config.needTraceId);
const resMessage = makeMessage(
response.data.error_details || response.data.message || '请求出错了!',
traceparent,
config.needTraceId
);
switch (response.status) {
case 502:
if (config.needMessage) bkMessage(resMessage);
Expand All @@ -45,39 +49,43 @@ const errorHandle = (response, config) => {
}
break;
case 401:
const { data } = response;
if (process.env.NODE_ENV === 'development') {
const url = new URL(data.login_url);
url.searchParams.set('c_url', location.href);
window.open(url.href, '_self');
} else {
const handleLoginExpire = () => {
window.location.href = `${window.bk_paas_host.replace(/\/$/g, '')}/login/`;
};
if (data?.has_plain) {
try {
if (data.login_url) {
// 初始化api 用于转换登入
if (config.url.includes('/commons/context/enhanced') && config.params.context_type === 'basic') {
const url = `${data.login_url.split('c_url=')[0]}c_url=${encodeURIComponent(location.href)}`;
window.open(url, '_self');
return;
}
const url = new URL(data.login_url);
const curl = url.searchParams.get('c_url');
url.protocol = location.protocol;
if (curl) {
url.searchParams.set('c_url', curl.replace(/^http:/, location.protocol));
window.showLoginModal({ loginUrl: url.href });
{
const { data } = response;
if (process.env.NODE_ENV === 'development') {
const url = new URL(data.login_url);
url.searchParams.set('c_url', location.href);
window.open(url.href, '_self');
} else {
const handleLoginExpire = () => {
window.location.href = `${window.bk_paas_host.replace(/\/$/g, '')}/login/`;
};
if (data?.has_plain) {
try {
if (data.login_url) {
// 初始化api 用于转换登入
if (config.url.includes('/commons/context/enhanced') && config.params.context_type === 'basic') {
const url = `${data.login_url.split('c_url=')[0]}c_url=${encodeURIComponent(location.href)}`;
window.open(url, '_self');
return;
}
const url = new URL(data.login_url);
const curl = url.searchParams.get('c_url');
url.protocol = location.protocol;
if (curl) {
url.searchParams.set('c_url', curl.replace(/^http:/, location.protocol));
window.showLoginModal({ loginUrl: url.href });
} else {
window.showLoginModal({ loginUrl: data.login_url.replace(/^http:/, location.protocol) });
}
} else {
window.showLoginModal({ loginUrl: data.login_url.replace(/^http:/, location.protocol) });
handleLoginExpire();
}
} catch (_) {
handleLoginExpire();
}
} catch (_) {
} else {
handleLoginExpire();
}
} else {
handleLoginExpire();
}
}
break;
Expand Down
31 changes: 16 additions & 15 deletions bkmonitor/webpack/src/monitor-api/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,19 @@ const removePendingRequest = (method, url) => {
pendingRequest.delete(requestKey);
}
};

export const request = function (method, url) {
return function (id, params, config = {}) {
export const request = (method, url) => {
return (id, params, config = {}) => {
let newUrl = url;
let data = {};
const hasBizId = !(window.cc_biz_id === -1 || !window.cc_biz_id);
if (typeof id === 'number' || typeof id === 'string') {
newUrl = url.replace('{pk}', id);
data = params || {};
// biome-ignore lint/style/noParameterAssign:0
config = Object.assign({}, defaultConfig, config || {});
} else {
data = id || {};
// biome-ignore lint/style/noParameterAssign:0
config = Object.assign({}, defaultConfig, params || {});
}
const methodType = method.toLocaleLowerCase() || 'get';
Expand Down Expand Up @@ -115,29 +116,29 @@ export const request = function (method, url) {
return Promise.resolve(res.data);
})
.catch(err => {
const message = makeMessage(err.message, traceparent, config.needTraceId);
if (config.needMessage && err.message) {
const message = makeMessage(err.error_details || err.message, traceparent, config.needTraceId);
if (config.needMessage) {
bkMessage(message);
}
err.message && (err.message = message);
// !err.error_details && err.message && (err.message = message);
return Promise.reject(err);
});
}
Object.keys(data).forEach(key => {
const type = String(data[key]);
for (const value of Object.values(data)) {
const type = String(value);
if (type === '[object FileList]' || type === '[object File]') {
const formData = new FormData();
Object.keys(data).forEach(key => {
formData.append(key, data[key]);
});
for (const [key, val] of Object.entries(data)) {
formData.append(key, val);
}
data = formData;
config.headers = {
...config.headers,
'content-type': 'multipart/form-data',
productionTip: true,
};
}
});
}
if (config.needBiz && !Object.prototype.hasOwnProperty.call(data, 'bk_biz_id')) {
if (data instanceof FormData) {
if (hasBizId) {
Expand Down Expand Up @@ -166,11 +167,11 @@ export const request = function (method, url) {
return Promise.resolve(res.data);
})
.catch(err => {
const message = makeMessage(err.message || '', traceparent, config.needTraceId);
if (config.needMessage && !noMessageCode.includes(err.code) && err.message) {
const message = makeMessage(err.error_details || err.message || '', traceparent, config.needTraceId);
if (config.needMessage && !noMessageCode.includes(err.code)) {
bkMessage(message);
}
err.message && (err.message = message);
// !err.error_details && err.message && (err.message = message);
return Promise.reject(err);
});
};
Expand Down
35 changes: 10 additions & 25 deletions bkmonitor/webpack/src/monitor-api/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,11 @@ export const setVue = function (instance) {
vue = instance;
};

export const bkMessage = (message, theme = 'error') => {
export const bkMessage = message => {
if (vue?.prototype?.$bkMessage) {
vue.prototype.$bkMessage({
message,
theme,
ellipsisLine: 0,
});
vue.prototype.$bkMessage(message);
} else {
vue.config.globalProperties.$Message({
message,
theme,
ellipsisLine: 0,
});
vue.config.globalProperties.$Message(message);
}
};

Expand All @@ -57,18 +49,11 @@ export const makeMessage = (message, traceparent, needTraceId) => {
if (list?.length) {
traceId = list[1];
}
const resMsg = needTraceId
? `
${traceId}
${message}
`
: message;
message &&
console.log(`
------------------【监控日志】------------------
【TraceID】:${traceId}
【Message】:${message}
----------------------------------------------
`);
return resMsg;
if (message && needTraceId && traceId && typeof message === 'object') {
return {
...message,
trace_id: traceId,
};
}
return message;
};
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,15 @@ import Vue from 'vue';

import bkMagicVue from 'bk-magic-vue';

import 'bk-magic-vue/dist/bk-magic-vue.min.css';
import { transformMessageProps } from './transform-message-props';

import 'bk-magic-vue/dist/bk-magic-vue.min.css';
Vue.use(bkMagicVue, { zIndex: 3000 });
const bkMessage = Vue.prototype.$bkMessage;
Vue.prototype.$bkMessage = (params: Record<string, any>) => {
const props = transformMessageProps(params);
return bkMessage(props);
};
// import {
// bkAlert,
// bkBadge,
Expand Down
67 changes: 67 additions & 0 deletions bkmonitor/webpack/src/monitor-pc/common/transform-message-props.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Tencent is pleased to support the open source community by making
* 蓝鲸智云PaaS平台 (BlueKing PaaS) available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* 蓝鲸智云PaaS平台 (BlueKing PaaS) is licensed under the MIT License.
*
* License for 蓝鲸智云PaaS平台 (BlueKing PaaS):
*
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
const MESSAGE_FIELD = 'popup_message';
const MESSAGE_THEME_LIST = ['error', 'warning'];
/**
*
* @param props { theme: string, message: Record<string, any>} | Record<string, any>
* @returns Record<string, any>
*/
export const transformMessageProps = (params: Record<string, any>) => {
let props = params;
if (!props || typeof props !== 'object') return props;
if (MESSAGE_FIELD in props) {
props = {
message: props,
};
}
if (props.message && typeof props.message !== 'string' && MESSAGE_FIELD in props.message) {
return {
actions: [
{
id: 'assistant',
disabled: !props.message.assistant,
},
{
id: 'details',
disabled: false,
},
],
message: {
code: props.message.exc_code || props.message.code,
overview: props.message.overview || props.message.overview,
suggestion: props.message.suggestion || '',
type: 'json',
details: JSON.stringify({ ...props.message }),
assistant: props.message.assistant || undefined,
},
theme: MESSAGE_THEME_LIST.includes(props.message.popup_message) ? props.message.popup_message : 'error',
ellipsisLine: 2,
ellipsisCopy: true,
};
}
return props;
};
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ export default class CustomEscalationSet extends Vue<MonitorVue> {
// 自定义指标
result = await createCustomTimeSeries({ ...params, ...addParams }, { needMessage: false }).catch(err => ({
time_series_group_id: '',
message: err.message,
message: err.error_details || err.message,
code: err.code,
}));
this.handleToDetail(result.time_series_group_id);
Expand All @@ -536,7 +536,7 @@ export default class CustomEscalationSet extends Vue<MonitorVue> {
// 名称报错
this.rule.name = true;
this.rule.nameTips = result.message;
} else if (!!result.code) {
} else if (result.code) {
this.$bkMessage({ message: result.message, theme: 'error' });
}
this.disableSubmit = false;
Expand Down
31 changes: 31 additions & 0 deletions bkmonitor/webpack/src/trace/common/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Tencent is pleased to support the open source community by making
* 蓝鲸智云PaaS平台 (BlueKing PaaS) available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* 蓝鲸智云PaaS平台 (BlueKing PaaS) is licensed under the MIT License.
*
* License for 蓝鲸智云PaaS平台 (BlueKing PaaS):
*
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { Message } from 'bkui-vue';
import { transformMessageProps } from 'monitor-pc/common/transform-message-props';
export const bkUiMessage = (params: Record<string, any>) => {
const props = transformMessageProps(params);
return Message(props);
};
4 changes: 2 additions & 2 deletions bkmonitor/webpack/src/trace/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ import 'monitor-common/polyfill';
import i18n from './i18n/i18n';
import { createApp } from 'vue';

import { Message } from 'bkui-vue';
import Api from 'monitor-api/api';
import { setVue } from 'monitor-api/utils/index';
import { immediateRegister } from 'monitor-common/service-worker/service-wroker';
import { getUrlParam, mergeSpaceList, setGlobalBizId } from 'monitor-common/utils';

import { bkUiMessage } from './common/message';
import directives from './directive/index';
import App from './pages/app';
import router from './router/router';
Expand All @@ -58,7 +58,7 @@ if (window.__POWERED_BY_BK_WEWEB__) {
app.use(store).use(router).use(i18n).use(directives).mount('#app');
app.config.globalProperties = {
$api: Api,
$Message: Message,
$Message: bkUiMessage,
$authorityStore: useAuthorityStore(),
} as any;
} else {
Expand Down

0 comments on commit 288a8b5

Please sign in to comment.