sunpengfei
2025-08-13 37fe2cc6c007dae986ece6346408d6541078baa9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FlexJobApi.Core
{
    public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
    {
        private readonly IServiceScope serviceScope;
        private readonly IRepository<ExceptionLog, LogDbContextLocator> rep;
 
        public LogExceptionHandler(IServiceScopeFactory scopeFactory)
        {
            serviceScope = scopeFactory.CreateScope();
            rep = serviceScope.ServiceProvider.GetRequiredService<IRepository<ExceptionLog, LogDbContextLocator>>();
        }
 
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            Console.WriteLine(App.User);
            await rep.InsertNowAsync(new ExceptionLog
            {
                Id = IDGen.NextID(),
                TraceId = App.GetTraceId(),
                Type = context.Exception.GetType().Name,
                Message = context.Exception.Message,
                StackTrace = context.Exception.StackTrace,
                CreatedTime = DateTime.Now,
            });
            if (context.Exception.InnerException != null)
            {
                await rep.InsertNowAsync(new ExceptionLog
                {
                    Id = IDGen.NextID(),
                    TraceId = App.GetTraceId(),
                    Type = context.Exception.InnerException.GetType().Name,
                    Message = context.Exception.InnerException.Message,
                    StackTrace = context.Exception.InnerException.StackTrace,
                    CreatedTime = DateTime.Now,
                });
            }
        }
    }
}