errorLog.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import type { ErrorLogInfo } from '/#/store';
  2. import { defineStore } from 'pinia';
  3. import { store } from '/@/store';
  4. import { formatToDateTime } from '/@/utils/dateUtil';
  5. import projectSetting from '/@/settings/projectSetting';
  6. import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
  7. export interface ErrorLogState {
  8. errorLogInfoList: Nullable<ErrorLogInfo[]>;
  9. errorLogListCount: number;
  10. }
  11. export const useErrorLogStore = defineStore({
  12. id: 'app-error-log',
  13. state: (): ErrorLogState => ({
  14. errorLogInfoList: null,
  15. errorLogListCount: 0,
  16. }),
  17. getters: {
  18. getErrorLogInfoList(): ErrorLogInfo[] {
  19. return this.errorLogInfoList || [];
  20. },
  21. getErrorLogListCount(): number {
  22. return this.errorLogListCount;
  23. },
  24. },
  25. actions: {
  26. addErrorLogInfo(info: ErrorLogInfo) {
  27. const item = {
  28. ...info,
  29. time: formatToDateTime(new Date()),
  30. };
  31. // [perf-base-v1] 上限保留最近 100 条,防止长时间运行错误日志无限累积占用内存
  32. this.errorLogInfoList = [item, ...(this.errorLogInfoList || [])].slice(0, 100);
  33. this.errorLogListCount += 1;
  34. },
  35. setErrorLogListCount(count: number): void {
  36. this.errorLogListCount = count;
  37. },
  38. /**
  39. * Triggered after ajax request error
  40. * @param error
  41. * @returns
  42. */
  43. addAjaxErrorInfo(error) {
  44. const { useErrorHandle } = projectSetting;
  45. if (!useErrorHandle) {
  46. return;
  47. }
  48. const errInfo: Partial<ErrorLogInfo> = {
  49. message: error.message,
  50. type: ErrorTypeEnum.AJAX,
  51. };
  52. if (error.response) {
  53. const { config: { url = '', data: params = '', method = 'get', headers = {} } = {}, data = {} } = error.response;
  54. errInfo.url = url;
  55. errInfo.name = 'Ajax Error!';
  56. errInfo.file = '-';
  57. errInfo.stack = JSON.stringify(data);
  58. errInfo.detail = JSON.stringify({ params, method, headers });
  59. }
  60. this.addErrorLogInfo(errInfo as ErrorLogInfo);
  61. },
  62. },
  63. });
  64. // Need to be used outside the setup
  65. export function useErrorLogStoreWithOut() {
  66. return useErrorLogStore(store);
  67. }