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.

65 lines
1.9 KiB

  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Shentun.WebApi.Service
  10. {
  11. public class ExceptionMiddleware
  12. {
  13. private readonly RequestDelegate next;
  14. private readonly ILogger logger;
  15. private IHostingEnvironment environment;
  16. public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostingEnvironment environment)
  17. {
  18. this.next = next;
  19. this.logger = logger;
  20. this.environment = environment;
  21. }
  22. public async Task Invoke(HttpContext context)
  23. {
  24. try
  25. {
  26. await next.Invoke(context);
  27. var features = context.Features;
  28. }
  29. catch (Exception e)
  30. {
  31. await HandleException(context, e);
  32. }
  33. }
  34. private async Task HandleException(HttpContext context, Exception e)
  35. {
  36. context.Response.StatusCode = 500;
  37. context.Response.ContentType = "text/json;charset=utf-8;";
  38. string error = "";
  39. void ReadException(Exception ex)
  40. {
  41. error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
  42. if (ex.InnerException != null)
  43. {
  44. ReadException(ex.InnerException);
  45. }
  46. }
  47. ReadException(e);
  48. if (environment.IsDevelopment())
  49. {
  50. var json = new { code = "ErrorCode", message = e.Message, detail = error };
  51. error = JsonConvert.SerializeObject(json);
  52. }
  53. else
  54. error = "抱歉,出错了";
  55. await context.Response.WriteAsync(error);
  56. }
  57. }
  58. }