ExceptionFilter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.Filters;
  5. using Microsoft.Extensions.Hosting;
  6. using Microsoft.Extensions.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace Ropin.Environmentally.AlarmService.Filters
  13. {
  14. public class ExceptionFilter : IExceptionFilter
  15. {
  16. public IWebHostEnvironment Environment { get; }
  17. public ILogger Logger { get; }
  18. public ExceptionFilter(IWebHostEnvironment env, ILogger<Program> logger)
  19. {
  20. Environment = env;
  21. Logger = logger;
  22. }
  23. public void OnException(ExceptionContext context)
  24. {
  25. var error = new ApiError();
  26. if (Environment.IsDevelopment())
  27. {
  28. error.Message = context.Exception.Message;
  29. error.Detail = context.Exception.ToString();
  30. }
  31. else
  32. {
  33. error.Message = "服务器出错";
  34. error.Detail = context.Exception.Message;
  35. }
  36. context.Result = new ObjectResult(error)
  37. {
  38. StatusCode = StatusCodes.Status500InternalServerError
  39. };
  40. StringBuilder sb = new StringBuilder();
  41. sb.AppendLine($"服务发生异常: {context.Exception.Message}");
  42. sb.AppendLine(context.Exception.ToString());
  43. Logger.LogCritical(sb.ToString());
  44. }
  45. }
  46. public class ApiError
  47. {
  48. public string Message { get; set; }
  49. public string Detail { get; set; }
  50. }
  51. }