GlobalExceptions.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.Filters;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace CZFW.CMS.Admin.App_Code
  10. {
  11. public class GlobalExceptions : IExceptionFilter
  12. {
  13. private readonly IHostingEnvironment _env;
  14. public GlobalExceptions(IHostingEnvironment env)
  15. {
  16. _env = env;
  17. }
  18. public void OnException(ExceptionContext context)
  19. {
  20. var json = new JsonErrorResponse();
  21. //这里面是自定义的操作记录日志
  22. if (context.Exception.GetType() == typeof(UserOperationException))
  23. {
  24. json.Message = context.Exception.Message;
  25. if (_env.IsDevelopment())
  26. {
  27. json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息
  28. }
  29. context.Result = new BadRequestObjectResult(json);//返回异常数据
  30. }
  31. else
  32. {
  33. json.Message = "发生了未知内部错误";
  34. if (_env.IsDevelopment())
  35. {
  36. json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息
  37. }
  38. context.Result = new InternalServerErrorObjectResult(json);
  39. }
  40. //采用log4net 进行错误日志记录
  41. LogHelper.ErrorLog(json.Message, context.Exception);
  42. }
  43. }
  44. public class InternalServerErrorObjectResult : ObjectResult
  45. {
  46. public InternalServerErrorObjectResult(object value) : base(value)
  47. {
  48. StatusCode = StatusCodes.Status500InternalServerError;
  49. }
  50. }
  51. }