Commit 5a2edfa1 by liimin

feat: 集成Sentry错误监控功能

添加Sentry错误监控支持,包括自动捕获网络错误和手动上报业务错误功能
- 新增Sentry初始化配置和错误上报工具函数
- 自动捕获并上报请求错误
- 支持小程序和Web环境的不同Sentry实现
- 添加类型定义和示例代码
- 更新文档和依赖配置
1 parent 50f8e1a9
// 小程序环境下使用 Sentry 的示例
const { Request } = require('../dist');
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置 - 在小程序环境中会自动使用 sentry-miniapp.js
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'miniprogram',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
function fetchData() {
return request.request({
url: '/api/data',
method: 'GET'
}).then(response => {
console.log('请求成功:', response);
return response;
}).catch(error => {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
throw error;
});
}
// 在小程序页面中使用
Page({
data: {
result: null,
loading: false,
error: null
},
onLoad: function() {
this.loadData();
},
loadData: function() {
this.setData({ loading: true, error: null });
fetchData()
.then(response => {
this.setData({
result: response.data,
loading: false
});
})
.catch(error => {
this.setData({
error: error.message,
loading: false
});
});
}
});
\ No newline at end of file \ No newline at end of file
import { Request } from '../src';
// 创建请求实例,必须提供 sentryDsn
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置(必填)
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'development',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
const fetchData = async () => {
try {
const response = await request.request({
url: '/api/data',
method: 'GET'
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 执行示例
(async () => {
console.log('开始测试必填 sentryDsn 功能...');
try {
await fetchData();
console.log('测试完成');
} catch (error) {
console.error('测试失败:', error);
}
// 尝试创建没有 sentryDsn 的实例(会抛出错误)
try {
// @ts-ignore - 故意忽略类型检查以演示运行时错误
const invalidRequest = new Request({
baseURL: 'https://api.example.com'
// 缺少必填的 sentryDsn
});
console.log('这行代码不应该被执行');
} catch (error) {
console.log('预期的错误:', error.message);
}
})();
\ No newline at end of file \ No newline at end of file
const { Request, Sentry } = require('../dist');
// 创建请求实例,并提供 Sentry DSN
const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000,
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0', // 替换为实际的 Sentry DSN
sentryOptions: {
environment: 'development',
release: '1.0.0',
debug: true
}
});
// 发起一个正常请求
request.get('/posts/1')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
});
// 发起一个会失败的请求(用于演示错误上报)
request.get('/non-existent-endpoint')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
// 错误已自动上报到 Sentry
});
// 手动上报错误示例
setTimeout(() => {
try {
// 模拟一个业务逻辑错误
throw new Error('业务逻辑处理失败');
} catch (error) {
// 手动上报错误到 Sentry
Sentry.reportBusinessError(error.message, {
userId: '12345',
action: 'processData',
timestamp: new Date().toISOString()
});
console.error('业务错误已上报到 Sentry');
}
}, 1000);
// 参数验证错误示例
function validateUserData(userData) {
if (!userData.name) {
Sentry.reportValidationError('用户名不能为空', userData);
return false;
}
return true;
}
// 测试参数验证
const userData = { id: 1, email: 'test@example.com' }; // 缺少 name 字段
if (!validateUserData(userData)) {
console.error('用户数据验证失败,错误已上报到 Sentry');
}
\ No newline at end of file \ No newline at end of file
import { Request, initSentry, reportBusinessError, reportNetworkError, reportValidationError } from '../src';
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'development',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起正常请求
const fetchData = async () => {
try {
const response = await request.request({
url: '/api/data',
method: 'GET'
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 发起一个会失败的请求(用于测试错误上报)
const fetchInvalidData = async () => {
try {
const response = await request.request({
url: '/api/invalid',
method: 'GET',
timeout: 3000 // 3秒超时
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 手动上报业务错误
const reportCustomBusinessError = () => {
const businessData = {
userId: 12345,
action: 'checkout',
cartItems: [
{ id: 1, name: 'Product 1', price: 99.99 },
{ id: 2, name: 'Product 2', price: 149.99 }
],
totalAmount: 249.98
};
reportBusinessError('结算流程异常', businessData);
};
// 手动上报参数验证错误
const reportCustomValidationError = () => {
const invalidParams = {
email: 'invalid-email',
password: '123', // 密码太短
age: -5 // 年龄不能为负数
};
reportValidationError('用户注册参数验证失败', invalidParams);
};
// 手动上报网络错误
const reportCustomNetworkError = () => {
const requestInfo = {
url: 'https://api.example.com/data',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: { key: 'value' },
timestamp: new Date().toISOString()
};
reportNetworkError('API 服务不可用', requestInfo);
};
// 执行示例
(async () => {
console.log('开始测试 Sentry 功能...');
// 测试自动错误上报
await fetchData().catch(console.error);
await fetchInvalidData().catch(console.error);
// 测试手动错误上报
reportCustomBusinessError();
reportCustomValidationError();
reportCustomNetworkError();
console.log('测试完成,请检查 Sentry 控制台查看上报的错误');
})();
\ No newline at end of file \ No newline at end of file
// uniapp环境下使用 Sentry 的示例
import { Request } from '../dist';
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置 - 在uniapp环境中会自动使用 sentry-miniapp.js
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'uniapp',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
function fetchData() {
return request.request({
url: '/api/data',
method: 'GET'
}).then(response => {
console.log('请求成功:', response);
return response;
}).catch(error => {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
throw error;
});
}
export default {
data() {
return {
result: null,
loading: false,
error: null
};
},
onLoad() {
this.loadData();
},
methods: {
loadData() {
this.loading = true;
this.error = null;
fetchData()
.then(response => {
this.result = response.data;
this.loading = false;
})
.catch(error => {
this.error = error.message;
this.loading = false;
});
}
}
};
\ No newline at end of file \ No newline at end of file
...@@ -95,6 +95,7 @@ ...@@ -95,6 +95,7 @@
baseURL: 'http://192.168.1.221:9898', baseURL: 'http://192.168.1.221:9898',
appId: 'dj_zhixin', appId: 'dj_zhixin',
appSecret: 'test-app-secret', appSecret: 'test-app-secret',
sentryDsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1',
}); });
// 测试白名单内请求 // 测试白名单内请求
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@sentry/browser": "^10.11.0",
"@types/qs": "^6.14.0", "@types/qs": "^6.14.0",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"qs": "^6.14.0" "qs": "^6.14.0"
...@@ -2498,6 +2499,75 @@ ...@@ -2498,6 +2499,75 @@
"win32" "win32"
] ]
}, },
"node_modules/@sentry-internal/browser-utils": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry-internal/browser-utils/-/browser-utils-10.11.0.tgz",
"integrity": "sha512-fnMlz5ntap6x4vRsLOHwPqXh7t82StgAiRt+EaqcMX0t9l8C0w0df8qwrONKXvE5GdHWTNFJj5qR15FERSkg3Q==",
"dependencies": {
"@sentry/core": "10.11.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@sentry-internal/feedback": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry-internal/feedback/-/feedback-10.11.0.tgz",
"integrity": "sha512-ADey51IIaa29kepb8B7aSgSGSrcyT7QZdRsN1rhitefzrruHzpSUci5c2EPIvmWfKJq8Wnvukm9BHXZXAAIOzA==",
"dependencies": {
"@sentry/core": "10.11.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@sentry-internal/replay": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry-internal/replay/-/replay-10.11.0.tgz",
"integrity": "sha512-t4M2bxMp2rKGK/l7bkVWjN+xVw9H9V12jAeXmO/Fskz2RcG1ZNLQnKSx/W/zCRMk8k7xOQFsfiApq+zDN+ziKA==",
"dependencies": {
"@sentry-internal/browser-utils": "10.11.0",
"@sentry/core": "10.11.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@sentry-internal/replay-canvas": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry-internal/replay-canvas/-/replay-canvas-10.11.0.tgz",
"integrity": "sha512-brWQ90IYQyZr44IpTprlmvbtz4l2ABzLdpP94Egh12Onf/q6n4CjLKaA25N5kX0uggHqX1Rs7dNaG0mP3ETHhA==",
"dependencies": {
"@sentry-internal/replay": "10.11.0",
"@sentry/core": "10.11.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@sentry/browser": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry/browser/-/browser-10.11.0.tgz",
"integrity": "sha512-qemaKCJKJHHCyGBpdLq23xL5u9Xvir20XN7YFTnHcEq4Jvj0GoWsslxKi5cQB2JvpYn62WxTiDgVLeQlleZhSg==",
"dependencies": {
"@sentry-internal/browser-utils": "10.11.0",
"@sentry-internal/feedback": "10.11.0",
"@sentry-internal/replay": "10.11.0",
"@sentry-internal/replay-canvas": "10.11.0",
"@sentry/core": "10.11.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@sentry/core": {
"version": "10.11.0",
"resolved": "https://registry.npmmirror.com/@sentry/core/-/core-10.11.0.tgz",
"integrity": "sha512-39Rxn8cDXConx3+SKOCAhW+/hklM7UDaz+U1OFzFMDlT59vXSpfI6bcXtNiFDrbOxlQ2hX8yAqx8YRltgSftoA==",
"engines": {
"node": ">=18"
}
},
"node_modules/@sinclair/typebox": { "node_modules/@sinclair/typebox": {
"version": "0.27.8", "version": "0.27.8",
"resolved": "https://registry.npmmirror.com/@sinclair/typebox/-/typebox-0.27.8.tgz", "resolved": "https://registry.npmmirror.com/@sinclair/typebox/-/typebox-0.27.8.tgz",
......
...@@ -38,6 +38,7 @@ ...@@ -38,6 +38,7 @@
"typescript": "^5.9.2" "typescript": "^5.9.2"
}, },
"dependencies": { "dependencies": {
"@sentry/browser": "^7.101.1",
"@types/qs": "^6.14.0", "@types/qs": "^6.14.0",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"qs": "^6.14.0" "qs": "^6.14.0"
......
...@@ -3,6 +3,7 @@ import type { Adapter } from './types'; ...@@ -3,6 +3,7 @@ import type { Adapter } from './types';
import webAdapter from './adapters/web'; import webAdapter from './adapters/web';
import miniprogramAdapter from './adapters/miniprogram'; import miniprogramAdapter from './adapters/miniprogram';
import uniappAdapter from './adapters/uniapp'; import uniappAdapter from './adapters/uniapp';
import { detectEnvironment, EnvironmentType } from '../utils';
// 重新导出签名相关功能 // 重新导出签名相关功能
export { generateSignature, type SignatureOptions, type SignatureResult } from '../signature'; export { generateSignature, type SignatureOptions, type SignatureResult } from '../signature';
...@@ -13,12 +14,15 @@ export { generateSignature, type SignatureOptions, type SignatureResult } from ' ...@@ -13,12 +14,15 @@ export { generateSignature, type SignatureOptions, type SignatureResult } from '
* @returns {Adapter} 适配器函数 * @returns {Adapter} 适配器函数
*/ */
export function getAdapter(options?: any): Adapter { export function getAdapter(options?: any): Adapter {
// 使用环境检测函数选择合适的适配器
const env = detectEnvironment();
// 返回适配器函数,但不直接调用它 // 返回适配器函数,但不直接调用它
// 这样在实际请求时,适配器会接收完整的请求配置(包含httpOptions) // 这样在实际请求时,适配器会接收完整的请求配置(包含httpOptions)
if (typeof wx !== 'undefined' && wx && 'request' in wx) { if (env === EnvironmentType.MINIPROGRAM) {
// 小程序环境 // 小程序环境
return miniprogramAdapter; return miniprogramAdapter;
} else if (typeof uni !== 'undefined' && uni && 'request' in uni) { } else if (env === EnvironmentType.UNIAPP) {
// uniapp环境 // uniapp环境
return uniappAdapter; return uniappAdapter;
} else { } else {
......
...@@ -27,12 +27,20 @@ class Defaults implements RequestConfig { ...@@ -27,12 +27,20 @@ class Defaults implements RequestConfig {
signatureFunc?: typeof generateSignature; signatureFunc?: typeof generateSignature;
httpOptions?: any; httpOptions?: any;
returnAll?: boolean; returnAll?: boolean;
// Sentry 配置
sentryDsn: string;
sentryOptions?: Record<string, any>;
/** /**
* 创建默认配置实例 * 创建默认配置实例
* @param config 用户提供的配置 * @param config 用户提供的配置
*/ */
constructor(config: Partial<RequestConfig> = {}) { constructor(config: Partial<RequestConfig> = {}) {
// 检查必填参数
if (!config.sentryDsn) {
throw new Error('sentryDsn is required for initialization');
}
// 基础配置 // 基础配置
this.baseURL = config.baseURL || ""; this.baseURL = config.baseURL || "";
this.timeout = config.timeout || 5000; this.timeout = config.timeout || 5000;
...@@ -42,6 +50,7 @@ class Defaults implements RequestConfig { ...@@ -42,6 +50,7 @@ class Defaults implements RequestConfig {
}; };
this.appId = config.appId || ""; this.appId = config.appId || "";
this.appSecret = config.appSecret || ""; this.appSecret = config.appSecret || "";
this.sentryDsn = config.sentryDsn; // 设置必填的 sentryDsn
// 重试配置 // 重试配置
this.retries = config.retries ?? 0; // 默认不重试 this.retries = config.retries ?? 0; // 默认不重试
...@@ -55,6 +64,7 @@ class Defaults implements RequestConfig { ...@@ -55,6 +64,7 @@ class Defaults implements RequestConfig {
if (config.params) this.params = { ...config.params }; if (config.params) this.params = { ...config.params };
if (config.signatureFunc) this.signatureFunc = config.signatureFunc; if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
if (config.httpOptions) this.httpOptions = config.httpOptions; if (config.httpOptions) this.httpOptions = config.httpOptions;
if (config.sentryOptions) this.sentryOptions = config.sentryOptions;
// 合并其他用户提供的配置 // 合并其他用户提供的配置
Object.keys(config).forEach(key => { Object.keys(config).forEach(key => {
......
import { reportNetworkError } from './sentry';
/** /**
* 请求错误类 * 请求错误类
*/ */
...@@ -19,18 +21,41 @@ export class RequestError extends Error { ...@@ -19,18 +21,41 @@ export class RequestError extends Error {
// 确保instanceof正常工作 // 确保instanceof正常工作
Object.setPrototypeOf(this, RequestError.prototype); Object.setPrototypeOf(this, RequestError.prototype);
// 如果配置中包含 sentryDsn,则上报错误到 Sentry
if (config && config.sentryDsn) {
this.reportToSentry();
}
}
/**
* 将错误上报到 Sentry
*/
reportToSentry(): void {
const errorInfo = {
code: this.code,
url: this.config?.url,
method: this.config?.method,
params: this.config?.params,
status: this.response?.status,
statusText: this.response?.statusText,
responseData: this.response?.data
};
reportNetworkError(this.message, errorInfo);
} }
/** /**
* 创建网络错误 * 创建网络错误
*/ */
static createNetworkError(message: string, config: any, request?: any): RequestError { static createNetworkError(message: string, config: any, request?: any): RequestError {
return new RequestError( const error = new RequestError(
message || '网络错误', message || '网络错误',
'NETWORK_ERROR', 'NETWORK_ERROR',
config, config,
request request
); );
return error;
} }
/** /**
......
import Request from './request'; import Request from './request';
import Defaults from './defaults'; import Defaults from './defaults';
import * as Sentry from './sentry';
// 导出主类 // 导出主类
export default Request; export default Request;
// 导出 Defaults 类,方便用户直接使用 // 导出 Defaults 类,方便用户直接使用
export { Defaults }; export { Defaults, Sentry };
// 导出类型定义 // 导出类型定义
export type { RequestConfig, ResponseData, RequestHeaders } from './types';
\ No newline at end of file \ No newline at end of file
export type { RequestConfig, ResponseData, RequestHeaders } from './types';
export type { SentryOptions, ErrorReportOptions } from './sentry';
\ No newline at end of file \ No newline at end of file
import * as Sentry from './sentry-miniapp'
// 仅使用ES模块导出
export { Sentry }
\ No newline at end of file \ No newline at end of file
// Type definitions for sentry-miniapp.js
// 导出所有Sentry相关的类型和函数
declare namespace Sentry {
// 基本配置接口
interface Options {
dsn?: string;
environment?: string;
release?: string;
debug?: boolean;
[key: string]: any;
}
// 错误级别类型
type SeverityLevel = 'fatal' | 'error' | 'warning' | 'log' | 'info' | 'debug';
// 错误捕获和上报相关函数
function init(options: Options): void;
function captureException(error: Error | string, options?: any): string;
function captureMessage(message: string, options?: any): string;
function captureEvent(event: any): string;
// 上下文相关函数
function setTag(key: string, value: string): void;
function setTags(tags: Record<string, string>): void;
function setExtra(key: string, value: any): void;
function setExtras(extras: Record<string, any>): void;
function setUser(user: Record<string, any> | null): void;
function setContext(name: string, context: Record<string, any> | null): void;
// Scope相关函数
function withScope(callback: (scope: any) => void): void;
// 其他可能的辅助函数
function addBreadcrumb(breadcrumb: any): void;
function configureScope(callback: (scope: any) => void): void;
}
export = Sentry;
export as namespace Sentry;
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
...@@ -9,9 +9,9 @@ export function addMethodAliases(instance: any): void { ...@@ -9,9 +9,9 @@ export function addMethodAliases(instance: any): void {
(["get", "post", "put", "delete", "patch"] as const).forEach((method) => { (["get", "post", "put", "delete", "patch"] as const).forEach((method) => {
if (method === "get" || method === "delete") { if (method === "get" || method === "delete") {
// 对于GET、DELETE方法 // 对于GET、DELETE方法
instance[method] = function ( instance[method] = function (this: any,
url: string, url: string,
config: RequestConfig = {} config: RequestConfig = { sentryDsn: this.defaults.sentryDsn }
) { ) {
return this.request({ return this.request({
url, url,
...@@ -21,10 +21,10 @@ export function addMethodAliases(instance: any): void { ...@@ -21,10 +21,10 @@ export function addMethodAliases(instance: any): void {
}; };
} else { } else {
// 对于POST、PUT、PATCH方法 // 对于POST、PUT、PATCH方法
instance[method] = function ( instance[method] = function (this: any,
url: string, url: string,
data?: any, data?: any,
config: RequestConfig = {} config: RequestConfig = { sentryDsn: this.defaults.sentryDsn }
) { ) {
return this.request({ return this.request({
url, url,
......
...@@ -10,10 +10,15 @@ import { getAdapter, type Adapter } from "./adapter"; ...@@ -10,10 +10,15 @@ import { getAdapter, type Adapter } from "./adapter";
import { dispatchEvent } from "./events"; import { dispatchEvent } from "./events";
import { sendRequestWithRetry } from "./retry"; import { sendRequestWithRetry } from "./retry";
import { addMethodAliases } from "./methods"; import { addMethodAliases } from "./methods";
import { preloadWhitelist, checkWhitelist, isWhitelistPreloaded } from "./whitelist"; import {
preloadWhitelist,
checkWhitelist,
isWhitelistPreloaded,
} from "./whitelist";
import { subscribeEvents } from "./events"; import { subscribeEvents } from "./events";
import Trace from "./traces"; import Trace from "./traces";
import Defaults from "./defaults"; import Defaults from "./defaults";
import { initSentry, reportNetworkError } from "./sentry";
interface Interceptors { interface Interceptors {
request: InterceptorManager<RequestConfig>; request: InterceptorManager<RequestConfig>;
...@@ -25,7 +30,7 @@ class Request { ...@@ -25,7 +30,7 @@ class Request {
interceptors: Interceptors; interceptors: Interceptors;
private adapter: Adapter; private adapter: Adapter;
private signFunc: (options: SignatureOptions) => SignatureResult; private signFunc: (options: SignatureOptions) => SignatureResult;
/** /**
* 获取白名单预加载状态 * 获取白名单预加载状态
* @returns 白名单是否已预加载 * @returns 白名单是否已预加载
...@@ -33,7 +38,7 @@ class Request { ...@@ -33,7 +38,7 @@ class Request {
static get isWhitelistPreloaded(): boolean { static get isWhitelistPreloaded(): boolean {
return isWhitelistPreloaded(); return isWhitelistPreloaded();
} }
/** /**
* 获取跟踪管理器实例 * 获取跟踪管理器实例
* @returns 跟踪管理器实例 * @returns 跟踪管理器实例
...@@ -42,7 +47,7 @@ class Request { ...@@ -42,7 +47,7 @@ class Request {
return Trace; return Trace;
} }
constructor(config: RequestConfig = {}) { constructor(config: RequestConfig) {
this.defaults = new Defaults(config); this.defaults = new Defaults(config);
// 创建拦截器实例 // 创建拦截器实例
...@@ -62,18 +67,20 @@ class Request { ...@@ -62,18 +67,20 @@ class Request {
// 自动订阅事件 // 自动订阅事件
subscribeEvents(this.defaults.events); subscribeEvents(this.defaults.events);
// 预加载白名单URL列表 // 预加载白名单URL列表
preloadWhitelist(); preloadWhitelist();
// 初始化 Sentry
initSentry(this.defaults.sentryDsn, this.defaults.sentryOptions || {});
} }
/** /**
* 发起请求 * 发起请求
* @param {Object} options 请求配置 * @param options 请求配置
* @returns {Promise & {abort: Function}} 可取消的请求Promise * @returns 可取消的请求Promise
*/ */
request<T = any>( request<T = any>(
options: RequestConfig = {} options: RequestConfig = { sentryDsn: this.defaults.sentryDsn }
): Promise<ResponseData<T>> & { abort?: () => void } { ): Promise<ResponseData<T>> & { abort?: () => void } {
// 合并配置 // 合并配置
const config = this.defaults.merge(options); const config = this.defaults.merge(options);
...@@ -132,7 +139,9 @@ class Request { ...@@ -132,7 +139,9 @@ class Request {
* @param {Object} config 请求配置 * @param {Object} config 请求配置
* @returns {Promise} * @returns {Promise}
*/ */
async dispatchRequest<T = any>(config: RequestConfig): Promise<ResponseData<T>> { async dispatchRequest<T = any>(
config: RequestConfig
): Promise<ResponseData<T>> {
// 添加签名 // 添加签名
const signedConfig = await this.addSignature(config); const signedConfig = await this.addSignature(config);
...@@ -153,7 +162,9 @@ class Request { ...@@ -153,7 +162,9 @@ class Request {
} }
// 使用预先确定的适配器,并添加重试逻辑 // 使用预先确定的适配器,并添加重试逻辑
return sendRequestWithRetry(this.adapter, signedConfig) as Promise<ResponseData<T>>; return sendRequestWithRetry(this.adapter, signedConfig) as Promise<
ResponseData<T>
>;
} }
/** /**
...@@ -170,7 +181,7 @@ class Request { ...@@ -170,7 +181,7 @@ class Request {
// 获取请求参数 // 获取请求参数
const params = { ...config.params }; const params = { ...config.params };
// 检查method参数是否在白名单中并更新参数 // 检查method参数是否在白名单中并更新参数
if (params.method) { if (params.method) {
const updatedParams = await checkWhitelist(params); const updatedParams = await checkWhitelist(params);
...@@ -178,7 +189,11 @@ class Request { ...@@ -178,7 +189,11 @@ class Request {
} }
// 使用预先确定的签名函数 // 使用预先确定的签名函数
const signature = this.signFunc({ appId, appSecret, params: config.params }); const signature = this.signFunc({
appId,
appSecret,
params: config.params,
});
// 添加签名到请求头 // 添加签名到请求头
config.headers = { config.headers = {
...config.headers, ...config.headers,
......
// 根据环境动态导入Sentry
import { detectEnvironment, EnvironmentType } from './utils';
// 预先导入可能使用的模块
import * as SentryBrowser from '@sentry/browser';
import { Sentry as SentryMiniapp } from './libs';
let Sentry: any;
// 使用环境检测函数选择合适的Sentry实现
const env = detectEnvironment();
if (env === EnvironmentType.MINIPROGRAM || env === EnvironmentType.UNIAPP) {
// 小程序或uniapp环境
Sentry = SentryMiniapp;
} else {
// Web环境
Sentry = SentryBrowser;
}
/**
* Sentry 初始化配置
*/
let isInitialized = false;
/**
* Sentry 初始化选项接口
*/
export interface SentryOptions {
environment?: string;
release?: string;
debug?: boolean;
tracesSampleRate?: number;
attachStacktrace?: boolean;
[key: string]: any;
}
/**
* 错误上报选项接口
*/
export interface ErrorReportOptions {
errorType?: string;
level?: Sentry.SeverityLevel;
fullObjectKey?: string;
tags?: Record<string, string>;
contexts?: Record<string, any>;
}
/**
* 初始化 Sentry
* @param dsn - Sentry DSN
* @param options - 初始化选项
*/
function initSentry(dsn: string, options: SentryOptions = {}) {
try {
Sentry.init({
dsn,
// 默认配置
tracesSampleRate: 1.0,
// 合并用户配置
...options
});
isInitialized = true;
console.log('Sentry initialized successfully');
} catch (error) {
console.error('Failed to initialize Sentry:', error);
}
}
/**
* 检查 Sentry 是否已初始化
* @returns {boolean} 是否已初始化
*/
function isSentryInitialized() {
return isInitialized;
}
/**
* 通用 Sentry 错误上报方法
* 1. 遍历参数对象的每一项,分别作为自定义参数上报
* 2. 将整个对象 JSON.stringify 后作为特殊参数一起上报
* @param errorMessage - 错误信息
* @param customParams - 自定义参数对象
* @param options - 可选配置
*/
function reportSentryError(errorMessage: string, customParams: Record<string, any> = {}, options: ErrorReportOptions = {}) {
if (!isInitialized) {
console.warn('Sentry is not initialized. Error not reported:', errorMessage);
return;
}
const {
errorType = 'general_error',
level = 'error',
fullObjectKey = 'full_params',
tags = {},
contexts = {}
} = options;
try {
// 第一步:遍历参数对象的每一项,分别作为自定义参数上报
Object.keys(customParams).forEach(key => {
const value = customParams[key];
// 如果值是对象,转换为 JSON 字符串
const processedValue = typeof value === 'object' && value !== null
? JSON.stringify(value)
: value;
// 设置为上下文信息(每个参数单独设置)
Sentry.setContext(key, {
value: processedValue,
originalType: typeof value,
timestamp: new Date().toISOString()
});
});
// 第二步:将整个对象 JSON.stringify 后作为特殊参数上报
const fullObjectString = JSON.stringify(customParams);
Sentry.setContext(fullObjectKey, {
data: fullObjectString,
type: 'full_object',
size: fullObjectString.length,
timestamp: new Date().toISOString()
});
// 如果完整对象字符串不太长,也设置为用户属性
if (fullObjectString.length <= 1000) {
Sentry.setUser({
[fullObjectKey]: fullObjectString
});
}
// 设置错误类型标签
Sentry.setTag('error_type', errorType);
// 设置参数统计标签
Sentry.setTag('params_count', String(Object.keys(customParams).length));
Sentry.setTag('full_object_size', fullObjectString.length > 1000 ? 'large' : 'normal');
// 设置额外的标签
Object.keys(tags).forEach(tagKey => {
Sentry.setTag(tagKey, String(tags[tagKey]));
});
// 设置额外的上下文
Object.keys(contexts).forEach(contextKey => {
Sentry.setContext(contextKey, contexts[contextKey]);
});
// 设置错误级别 - 使用 configureScope 设置级别
Sentry.withScope((scope: any) => {
scope.setLevel(level);
});
// 上报错误
Sentry.captureException(new Error(errorMessage));
} catch (error) {
console.error('Sentry 错误上报失败:', error);
}
}
/**
* 简化版本 - 只设置自定义参数和基本错误信息
* @param errorMessage - 错误信息
* @param customParams - 自定义参数对象
* @param level - 错误级别
*/
function reportError(errorMessage: string, customParams: Record<string, any> = {}, level: Sentry.SeverityLevel = 'error') {
return reportSentryError(errorMessage, customParams, { level });
}
/**
* 专门用于参数验证失败的错误上报
* @param errorMessage - 错误信息
* @param params - 参数对象
*/
function reportValidationError(errorMessage: string, params: Record<string, any> = {}) {
return reportSentryError(errorMessage, params, {
errorType: 'validation_error',
level: 'warning'
});
}
/**
* 专门用于网络请求错误的上报
* @param errorMessage - 错误信息
* @param requestInfo - 请求信息
*/
function reportNetworkError(errorMessage: string, requestInfo: Record<string, any> = {}) {
return reportSentryError(errorMessage, requestInfo, {
errorType: 'network_error',
fullObjectKey: 'request_info'
});
}
/**
* 专门用于业务逻辑错误的上报
* @param errorMessage - 错误信息
* @param businessData - 业务数据
*/
function reportBusinessError(errorMessage: string, businessData: Record<string, any> = {}) {
return reportSentryError(errorMessage, businessData, {
errorType: 'business_error',
fullObjectKey: 'business_data'
});
}
export {
initSentry,
isSentryInitialized,
reportSentryError,
reportError,
reportValidationError,
reportNetworkError,
reportBusinessError
};
...@@ -38,6 +38,8 @@ export interface RequestConfig extends RetryConfig { ...@@ -38,6 +38,8 @@ export interface RequestConfig extends RetryConfig {
events?: Record<string, Function>; // 事件订阅配置 events?: Record<string, Function>; // 事件订阅配置
httpOptions?: any; // HTTP选项 httpOptions?: any; // HTTP选项
returnAll?: boolean; // 是否返回完整响应 returnAll?: boolean; // 是否返回完整响应
sentryDsn: string; // Sentry DSN 配置(必填)
sentryOptions?: Record<string, any>; // Sentry 初始化选项
} }
export interface SignatureOptions { export interface SignatureOptions {
......
/**
* 环境检测工具函数
*/
/**
* 环境类型枚举
*/
export enum EnvironmentType {
WEB = 'web',
MINIPROGRAM = 'miniprogram',
UNIAPP = 'uniapp'
}
/**
* 检测当前运行环境
* 使用IIFE模式,确保只执行一次环境检测
*/
export const detectEnvironment = (() => {
// 缓存检测结果
let detectedEnv: EnvironmentType | null = null;
// 返回实际的检测函数
return (): EnvironmentType => {
// 如果已经检测过,直接返回缓存结果
if (detectedEnv !== null) {
return detectedEnv;
}
// 执行环境检测
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
// 小程序环境
detectedEnv = EnvironmentType.MINIPROGRAM;
} else if (typeof uni !== 'undefined' && uni && 'request' in uni) {
// uniapp环境
detectedEnv = EnvironmentType.UNIAPP;
} else {
// Web环境
detectedEnv = EnvironmentType.WEB;
}
return detectedEnv;
};
})();
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test UMD Module</title>
</head>
<body>
<h1>Testing UMD Module</h1>
<div id="result"></div>
<script src="./dist/index.umd.js"></script>
<script>
try {
// 尝试访问库
console.log('Library loaded:', window.glskFetch);
document.getElementById('result').innerHTML = 'Library loaded successfully!';
} catch (error) {
console.error('Error loading library:', error);
document.getElementById('result').innerHTML = 'Error: ' + error.message;
}
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!