Commit 79bd0232 by liimin

style: 为控制台日志添加颜色和图标标记

为错误、警告、信息和成功日志添加颜色和图标标记,提高日志的可读性和辨识度
1 parent 33b1fd35
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试500错误处理</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.test-section {
margin: 20px 0;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
}
.result {
margin-top: 10px;
padding: 10px;
border-radius: 3px;
font-family: monospace;
white-space: pre-wrap;
}
.success { background-color: #d4edda; color: #155724; }
.error { background-color: #f8d7da; color: #721c24; }
.info { background-color: #d1ecf1; color: #0c5460; }
button {
padding: 10px 20px;
margin: 5px;
border: none;
border-radius: 3px;
cursor: pointer;
background-color: #007bff;
color: white;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>测试500错误处理</h1>
<p>这个页面用于测试修复后的HTTP状态码错误处理是否能正确触发error事件。</p>
<div class="test-section">
<h3>测试1: 500服务器错误(带重试)</h3>
<button onclick="test500Error()">发送500错误请求</button>
<div id="result500" class="result"></div>
</div>
<div class="test-section">
<h3>测试1B: 500服务器错误(无重试)</h3>
<button onclick="test500ErrorNoRetry()">发送500错误请求(无重试)</button>
<div id="result500NoRetry" class="result"></div>
</div>
<div class="test-section">
<h3>测试2: 404客户端错误</h3>
<button onclick="test404Error()">发送404错误请求</button>
<div id="result404" class="result"></div>
</div>
<div class="test-section">
<h3>测试3: 业务错误响应</h3>
<button onclick="testBusinessError()">发送业务错误请求</button>
<div id="resultBusiness" class="result"></div>
</div>
<div class="test-section">
<h3>测试4: 404错误响应</h3>
<button onclick="test404Error()">发送404错误请求</button>
<div id="result404" class="result"></div>
</div>
<div class="test-section">
<h3>测试5: 200成功响应</h3>
<button onclick="testSuccess()">发送成功请求</button>
<div id="resultSuccess" class="result"></div>
</div>
<div class="test-section">
<h3>事件监听日志</h3>
<button onclick="clearLogs()">清空日志</button>
<div id="eventLogs" class="result info"></div>
</div>
<script src="../dist/index.umd.js"></script>
<script>
// 创建请求实例
const request = new GlskToolkit.Request({
baseURL: 'http://localhost:3002',
timeout: 10000,
events: {
request: (data, config) => {
addLog('🚀 REQUEST事件触发', { url: config.url, method: config.method });
},
response: (data, config) => {
addLog('📥 RESPONSE事件触发', { status: data.status, url: config.url });
},
success: (data, config) => {
addLog('✅ SUCCESS事件触发', { data, url: config.url });
},
error: (data, config) => {
addLog('❌ ERROR事件触发', { data, url: config.url });
},
logout: (data, config) => {
addLog('🚪 LOGOUT事件触发', { data, url: config.url });
}
}
});
function addLog(title, data) {
const logs = document.getElementById('eventLogs');
const timestamp = new Date().toLocaleTimeString();
logs.textContent += `[${timestamp}] ${title}\n${JSON.stringify(data, null, 2)}\n\n`;
logs.scrollTop = logs.scrollHeight;
}
function clearLogs() {
document.getElementById('eventLogs').textContent = '';
}
function showResult(elementId, type, message, data = null) {
const element = document.getElementById(elementId);
element.className = `result ${type}`;
element.textContent = message;
if (data) {
element.textContent += '\n\n' + JSON.stringify(data, null, 2);
}
}
async function test500Error() {
showResult('result500', 'info', '正在发送500错误请求(带重试)...');
try {
const response = await request.get('/api/test-500', {
retry: {
retries: 2, // 重试2次
retryDelay: 500, // 重试延迟500ms
shouldResetTimeout: true
}
});
showResult('result500', 'success', '请求成功(这不应该发生)', response);
} catch (error) {
showResult('result500', 'error', `捕获到错误: ${error.message}`, {
code: error.code,
status: error.response?.status,
statusText: error.response?.statusText
});
}
}
async function test500ErrorNoRetry() {
showResult('result500NoRetry', 'info', '正在发送500错误请求(无重试)...');
try {
const response = await request.get('/api/test-500'); // 不设置retry
showResult('result500NoRetry', 'success', '请求成功(这不应该发生)', response);
} catch (error) {
showResult('result500NoRetry', 'error', `捕获到错误: ${error.message}`, {
code: error.code,
status: error.response?.status,
statusText: error.response?.statusText
});
}
}
async function test404Error() {
showResult('result404', 'info', '正在发送404错误请求...');
try {
const response = await request.get('/api/not-found');
showResult('result404', 'success', '请求成功(这不应该发生)', response);
} catch (error) {
showResult('result404', 'error', `捕获到错误: ${error.message}`, {
code: error.code,
status: error.response?.status,
statusText: error.response?.statusText
});
}
}
async function testSuccess() {
showResult('resultSuccess', 'info', '正在发送成功请求...');
try {
const response = await request.get('/api/test-success');
showResult('resultSuccess', 'success', '请求成功', response);
} catch (error) {
showResult('resultSuccess', 'error', `请求失败: ${error.message}`, error);
}
}
async function testBusinessError() {
showResult('resultBusiness', 'info', '正在发送业务错误请求...');
try {
const response = await request.get('/api/test-error');
showResult('resultBusiness', 'success', '请求成功(这不应该发生)', response);
} catch (error) {
showResult('resultBusiness', 'error', `捕获到错误: ${error.message}`, {
code: error.code,
status: error.response?.status,
statusText: error.response?.statusText
});
}
}
async function test404Error() {
showResult('result404', 'info', '正在发送404错误请求...');
try {
const response = await request.get('/api/not-found');
showResult('result404', 'success', '请求成功(这不应该发生)', response);
} catch (error) {
showResult('result404', 'error', `捕获到错误: ${error.message}`, {
code: error.code,
status: error.response?.status,
statusText: error.response?.statusText
});
}
}
// 页面加载时显示初始信息
addLog('📋 页面加载完成', { message: '准备测试HTTP状态码错误处理' });
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -35,7 +35,7 @@ export class PubSub { ...@@ -35,7 +35,7 @@ export class PubSub {
try { try {
callback(...args); callback(...args);
} catch (error) { } catch (error) {
console.error(`Error in event handler for ${event}:`, error); console.error('\x1b[31m❌ %s\x1b[0m', `Error in event handler for ${event}:`, error);
} }
}); });
} }
......
...@@ -226,7 +226,7 @@ class Request { ...@@ -226,7 +226,7 @@ class Request {
async addSignature(config: RequestConfig): Promise<RequestConfig> { async addSignature(config: RequestConfig): Promise<RequestConfig> {
const { appId, appSecret } = config; const { appId, appSecret } = config;
if (!appId || !appSecret) { if (!appId || !appSecret) {
console.warn("缺少签名所需的应用ID或密钥"); console.warn('\x1b[33m⚠️ %s\x1b[0m', "缺少签名所需的应用ID或密钥");
return config; return config;
} }
// 获取请求参数 // 获取请求参数
......
...@@ -35,7 +35,7 @@ export class PubSub { ...@@ -35,7 +35,7 @@ export class PubSub {
try { try {
callback(...args); callback(...args);
} catch (error) { } catch (error) {
console.error(`Error in event handler for ${event}:`, error); console.error('\x1b[31m❌ %s\x1b[0m', `Error in event handler for ${event}:`, error);
} }
}); });
} }
......
...@@ -62,9 +62,9 @@ function initSentry(dsn: string, options: SentryOptions = {}) { ...@@ -62,9 +62,9 @@ function initSentry(dsn: string, options: SentryOptions = {}) {
}); });
isInitialized = true; isInitialized = true;
console.log('Sentry initialized successfully'); console.log('\x1b[32m✅ %s\x1b[0m', 'Sentry initialized successfully');
} catch (error) { } catch (error) {
console.error('Failed to initialize Sentry:', error); console.error('\x1b[31m❌ %s\x1b[0m', 'Failed to initialize Sentry:', error);
} }
} }
...@@ -86,7 +86,7 @@ function isSentryInitialized() { ...@@ -86,7 +86,7 @@ function isSentryInitialized() {
*/ */
function reportSentryError(errorMessage: string, customParams: Record<string, any> = {}, options: ErrorReportOptions = {}) { function reportSentryError(errorMessage: string, customParams: Record<string, any> = {}, options: ErrorReportOptions = {}) {
if (!isInitialized) { if (!isInitialized) {
console.warn('Sentry is not initialized. Error not reported:', errorMessage); console.warn('\x1b[33m⚠️ %s\x1b[0m', 'Sentry is not initialized. Error not reported:', errorMessage);
return; return;
} }
...@@ -157,7 +157,7 @@ function reportSentryError(errorMessage: string, customParams: Record<string, an ...@@ -157,7 +157,7 @@ function reportSentryError(errorMessage: string, customParams: Record<string, an
// 上报错误 // 上报错误
Sentry.captureException(new Error(errorMessage)); Sentry.captureException(new Error(errorMessage));
} catch (error) { } catch (error) {
console.error('Sentry 错误上报失败:', error); console.error('\x1b[31m❌ %s\x1b[0m', 'Sentry 错误上报失败:', error);
} }
} }
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
* @Author: limin * @Author: limin
* @Date: 2025-09-09 09:49:02 * @Date: 2025-09-09 09:49:02
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-09-18 09:39:49 * @LastEditTime: 2025-09-19 21:06:54
* @FilePath: \glsk-toolkit\src\monitoring\traces.ts * @FilePath: \glsk-fetch\src\monitoring\traces.ts
*/ */
import { simpleGet } from '../utils/http'; import { simpleGet } from '../utils/http';
...@@ -105,7 +105,7 @@ export class TraceManager { ...@@ -105,7 +105,7 @@ export class TraceManager {
return this._processUrls(urls); return this._processUrls(urls);
} catch (error) { } catch (error) {
lastError = error; lastError = error;
console.warn(`获取配置失败 (尝试 ${attempt + 1}/${this.config.retryCount}):`, error); console.warn('\x1b[33m⚠️ %s\x1b[0m', `获取配置失败 (尝试 ${attempt + 1}/${this.config.retryCount}):`, error);
// 最后一次尝试不需要等待 // 最后一次尝试不需要等待
if (attempt < this.config.retryCount - 1) { if (attempt < this.config.retryCount - 1) {
...@@ -115,7 +115,7 @@ export class TraceManager { ...@@ -115,7 +115,7 @@ export class TraceManager {
} }
// 所有重试都失败了 // 所有重试都失败了
console.error('获取配置最终失败:', lastError); console.error('\x1b[31m❌ %s\x1b[0m', '获取配置最终失败:', lastError);
return []; return [];
} }
...@@ -193,11 +193,11 @@ export class TraceManager { ...@@ -193,11 +193,11 @@ export class TraceManager {
try { try {
const urls = await this.getTraceUrls(true); // 强制刷新缓存 const urls = await this.getTraceUrls(true); // 强制刷新缓存
isPreloaded = true; isPreloaded = true;
console.log('白名单URL预加载成功:', urls.length); console.log('\x1b[32m✅ %s\x1b[0m', '白名单URL预加载成功:', urls.length);
return urls; return urls;
} catch (error) { } catch (error) {
isPreloaded = false; isPreloaded = false;
console.error('白名单URL预加载失败:', error); console.error('\x1b[31m❌ %s\x1b[0m', '白名单URL预加载失败:', error);
return []; return [];
} }
} }
......
...@@ -21,7 +21,7 @@ export async function checkWhitelist(url: string, customAddress?: string): Promi ...@@ -21,7 +21,7 @@ export async function checkWhitelist(url: string, customAddress?: string): Promi
// 检查当前请求的URL是否在白名单中 // 检查当前请求的URL是否在白名单中
return whitelistUrls.includes(url); return whitelistUrls.includes(url);
} catch (error) { } catch (error) {
console.error('检查白名单URL失败:', error); console.error('\x1b[31m❌ %s\x1b[0m', '检查白名单URL失败:', error);
return false; return false;
} }
} }
...@@ -38,9 +38,9 @@ export async function preloadWhitelist(customAddress?: string): Promise<void> { ...@@ -38,9 +38,9 @@ export async function preloadWhitelist(customAddress?: string): Promise<void> {
Trace.updateConfig({ url: customAddress }); Trace.updateConfig({ url: customAddress });
} }
await Trace.preloadTraceUrls(); await Trace.preloadTraceUrls();
console.log('白名单URL预加载完成'); console.log('\x1b[32m✅ %s\x1b[0m', '白名单URL预加载完成');
} catch (error) { } catch (error) {
console.warn('白名单URL预加载失败:', error); console.warn('\x1b[33m⚠️ %s\x1b[0m', '白名单URL预加载失败:', error);
} }
} }
......
...@@ -34,7 +34,7 @@ class AbortSignalPolyfill { ...@@ -34,7 +34,7 @@ class AbortSignalPolyfill {
try { try {
l.listener(event); l.listener(event);
} catch (error) { } catch (error) {
console.warn('Error in event listener:', error); console.warn('\x1b[33m⚠️ %s\x1b[0m', 'Error in event listener:', error);
} }
}); });
} }
......
...@@ -41,7 +41,7 @@ export function sendRequestWithRetry( ...@@ -41,7 +41,7 @@ export function sendRequestWithRetry(
return adapter(config).catch((error: RequestError) => { return adapter(config).catch((error: RequestError) => {
// 调试信息 // 调试信息
console.log('重试调试信息:', { console.log('\x1b[36m🔍 %s\x1b[0m', '重试调试信息:', {
retryCount, retryCount,
retries, retries,
errorCode: error.code, errorCode: error.code,
...@@ -57,7 +57,7 @@ export function sendRequestWithRetry( ...@@ -57,7 +57,7 @@ export function sendRequestWithRetry(
(retryCondition ? Boolean(retryCondition(error)) : isRetryableError(error)); (retryCondition ? Boolean(retryCondition(error)) : isRetryableError(error));
if (shouldRetry) { if (shouldRetry) {
console.log(`请求失败,正在进行第${retryCount + 1}次重试...`); console.log('\x1b[33m🔄 %s\x1b[0m', `请求失败,正在进行第${retryCount + 1}次重试...`);
// 创建延迟Promise // 创建延迟Promise
const delayPromise = new Promise((resolve) => { const delayPromise = new Promise((resolve) => {
...@@ -77,7 +77,7 @@ export function sendRequestWithRetry( ...@@ -77,7 +77,7 @@ export function sendRequestWithRetry(
} }
// 不需要重试,触发error事件后抛出错误 // 不需要重试,触发error事件后抛出错误
console.log('重试最终失败,触发error事件'); console.log('\x1b[31m💥 %s\x1b[0m', '重试最终失败,触发error事件');
// 根据错误类型创建更准确的statusText // 根据错误类型创建更准确的statusText
let statusText = 'Unknown Error'; let statusText = 'Unknown Error';
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!