diff --git a/ds-wms-service/DS.Module.Core/Filters/GlobalExceptionsFilter.cs b/ds-wms-service/DS.Module.Core/Filters/GlobalExceptionsFilter.cs index 154ba3c1..6060a5ab 100644 --- a/ds-wms-service/DS.Module.Core/Filters/GlobalExceptionsFilter.cs +++ b/ds-wms-service/DS.Module.Core/Filters/GlobalExceptionsFilter.cs @@ -1,13 +1,13 @@ -using Microsoft.AspNetCore.Hosting; +using DS.Module.Core.Log; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; using NLog; +using SqlSugar; using System.Text; using System.Text.RegularExpressions; -using DS.Module.Core.Log; -using Microsoft.Extensions.DependencyInjection; -using SqlSugar; namespace DS.Module.Core.Filters; diff --git a/ds-wms-service/DS.WMS.JobService/ArgumentExceptionHandler.cs b/ds-wms-service/DS.WMS.JobService/ArgumentExceptionHandler.cs new file mode 100644 index 00000000..9d8edbcc --- /dev/null +++ b/ds-wms-service/DS.WMS.JobService/ArgumentExceptionHandler.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc; + +namespace DS.WMS.JobService +{ + public sealed class ArgumentExceptionHandler : IExceptionHandler + { + public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken) + { + httpContext.RequestServices.GetRequiredService>() + .LogError(exception, "Exception handled"); + if (exception is not ArgumentException) return false; + + httpContext.Response.StatusCode = 400; + await httpContext.Response.WriteAsJsonAsync(new + { + exception.Message + }, cancellationToken); + return true; + } + } +} diff --git a/ds-wms-service/DS.WMS.JobService/GlobalExceptionsFilter.cs b/ds-wms-service/DS.WMS.JobService/GlobalExceptionsFilter.cs new file mode 100644 index 00000000..0d31f837 --- /dev/null +++ b/ds-wms-service/DS.WMS.JobService/GlobalExceptionsFilter.cs @@ -0,0 +1,128 @@ +using DS.Module.Core.Log; +using DS.Module.Core; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace DS.WMS.JobService +{ + /// + /// 全局异常错误日志 + /// + public class GlobalExceptionsFilter : IExceptionFilter + { + private readonly IHostingEnvironment _env; + private readonly IServiceProvider _serviceProvider; + public GlobalExceptionsFilter(IHostingEnvironment env, IServiceProvider serviceProvider) + { + _env = env; + _serviceProvider = serviceProvider; + } + + public void OnException(ExceptionContext context) + { + var json = new JsonErrorResponse(); + + json.Message = context.Exception.Message; //错误信息 + if (_env.IsDevelopment()) + { + json.DevelopmentMessage = context.Exception.StackTrace; //堆栈信息 + } + + var result = DataResult.Failed(json.Message); + + var objectResult = new BadRequestObjectResult(result); + objectResult.StatusCode = (int?)StatusCodes.Status200OK; + context.Result = objectResult; + // context.Result = new InternalServerErrorObjectResult(json); + + //MiniProfiler.Current.CustomTiming("Errors:", json.Message); + //记录异常到日志 + StringBuilder exMsg = new(); + exMsg.AppendLine($"【异常方法:】{context.HttpContext.Request.Path}"); + exMsg.AppendLine($"【请求类型:】{context.HttpContext.Request.Method}"); + exMsg.AppendLine($"【异常错误:】{context.Exception.Message}"); + exMsg.AppendLine($"【堆栈跟踪:】{context.Exception.StackTrace}"); + + + #region 写入日志库 + + var className = context.Exception.TargetSite.DeclaringType?.FullName; + var groupCollection = Regex.Match(className, "<(.*?)>").Groups; + var methodName = ""; + if (groupCollection.Count > 1) + { + methodName = groupCollection[1].Value; + } + var exLog = new SysLogException() + { + ClassName = className, + MethodName = methodName, + ExceptionName = context.Exception.Message, + ExceptionMsg = context.Exception.Message, + ExceptionSource = context.Exception.Source, + StackTrace = context.Exception.StackTrace, + ParamsObj = context.Exception.TargetSite.GetParameters().ToString(), + }; + + + #endregion + + + // Logger.Log(NLog.LogLevel.Info, "异常信息:" + JsonConvert.SerializeObject(context.Exception)); + //采用log4net 进行错误日志记录 + //_loggerHelper.Error(json.Message, WriteLog(json.Message, context.Exception)); + + //_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); + } + + /// + /// 自定义返回格式 + /// + /// + /// + /// + public string WriteLog(string throwMsg, Exception ex) + { + return string.Format("【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}", new object[] + { + throwMsg, + ex.GetType().Name, ex.Message, ex.StackTrace + }); + } + } + + /// + /// + /// + public class InternalServerErrorObjectResult : ObjectResult + { + public InternalServerErrorObjectResult(object value) : base(value) + { + StatusCode = StatusCodes.Status500InternalServerError; + } + } + + /// + /// 返回错误信息 + /// + public class JsonErrorResponse + { + /// + /// 生产环境的消息 + /// + public string Message { get; set; } + + /// + /// 开发环境的消息 + /// + public string DevelopmentMessage { get; set; } + } +} diff --git a/ds-wms-service/DS.WMS.JobService/Program.cs b/ds-wms-service/DS.WMS.JobService/Program.cs index a99bbd63..bae07357 100644 --- a/ds-wms-service/DS.WMS.JobService/Program.cs +++ b/ds-wms-service/DS.WMS.JobService/Program.cs @@ -11,6 +11,7 @@ using DS.WMS.Core.HangfireJob.Interface; using DS.WMS.Core.HangfireJob.Method; var builder = Host.CreateApplicationBuilder(args); + var environment = builder.Environment.EnvironmentName; Console.WriteLine("ǰ:" + environment); //ע @@ -23,16 +24,24 @@ builder.Configuration.AddEnvironmentVariables(); //Autofacע builder.ConfigureContainer(new AutofacServiceProviderFactory(), builder => builder.RegisterModule(new AutofacModuleRegister())); - +builder.Services.AddExceptionHandler(); //ȫ쳣 builder.Services.AddUserModuleInstall(); //û builder.Services.AddRedisModuleInstall();//redis builder.Services.AddSqlSugarInstall(); builder.Services.AddSaasDbInstall();//ֿ //עhangfire builder.Services.AddWorkServiceHangfireModuleInstall(); -builder.Services.AddWindowsService(); + builder.Services.AddHostedService(); +// BackgroundService дδ쳣ֹͣ +builder.Services.Configure(hostOptions => +{ + hostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore; +}); +//ӦΪ Windows +builder.Services.AddWindowsService(); var host = builder.Build(); + host.Run(); diff --git a/ds-wms-service/DS.WMS.JobService/Worker.cs b/ds-wms-service/DS.WMS.JobService/Worker.cs index bd2e218b..002c4257 100644 --- a/ds-wms-service/DS.WMS.JobService/Worker.cs +++ b/ds-wms-service/DS.WMS.JobService/Worker.cs @@ -10,18 +10,7 @@ namespace DS.WMS.JobService private BackgroundJobServer _server; public Worker(ILogger logger) { - _logger = logger; - //using (new BackgroundJobServer()) - //{ - // new BackgroundJobServerOptions() - // { - - // Queues = new[] { "op", "task" } - // }; - //} - //Hangfire.GlobalConfiguration.Configuration.UseStorage(new MySqlStorage(AppSetting.app(new string[] { "HangfireSettings", "DbString" }))); - //. UseMySqlStorage(AppSetting.app(new string[] { "HangfireSettings", "DbString" })); - + _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -32,22 +21,21 @@ namespace DS.WMS.JobService ServerName = "WorkService", Queues = new[] { "op", "task" } }; - _server = new BackgroundJobServer(options); - while (!stoppingToken.IsCancellationRequested) { - - //using (var server = new BackgroundJobServer()) - //{ - // new BackgroundJobServerOptions() - // { - // ServerName = "WorkService", - // Queues = new[] { "op", "task" } - // }; - Console.WriteLine("Hangfire Server started. Press any key to exit..."); - Console.ReadKey(); - //} + try + { + _server = new BackgroundJobServer(options); + Console.WriteLine("Hangfire Server started. Press any key to exit..."); + Console.ReadKey(); + } + catch (Exception ex) + { + Console.WriteLine(ex); + await Task.Delay(1000); + } } + } } }