平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LogExceptionHandler.cs 959 B

4 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 
  2. //
  3. using MoYu.DependencyInjection;
  4. using MoYu.FriendlyException;
  5. using Microsoft.Extensions.Logging;
  6. namespace SafeCampus.Web.Core;
  7. /// <summary>
  8. /// 全局异常处理提供器
  9. /// </summary>
  10. public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
  11. {
  12. private readonly ILogger<LogExceptionHandler> _logger;
  13. public LogExceptionHandler(ILogger<LogExceptionHandler> logger)
  14. {
  15. _logger = logger;
  16. }
  17. public async Task OnExceptionAsync(ExceptionContext context)
  18. {
  19. var exception = context.Exception;//获取异常
  20. //如果异常类型不是友好异常
  21. if (exception.GetType() != typeof(AppFriendlyException))
  22. {
  23. _logger.LogError(exception, exception.Message);
  24. //重新定义异常
  25. context.Exception = new AppFriendlyException("系统异常,请联系管理员", ErrorCodeEnum.A0000);
  26. }
  27. await Task.CompletedTask;
  28. }
  29. }