【问题标题】:Exception Handling in MVC [closed]MVC 中的异常处理 [关闭]
【发布时间】:2021-07-29 16:23:39
【问题描述】:

如何处理 MVC 中的异常,以便在代码的任何位置发生异常时控制移动到特定点?请举例说明

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-core exception


【解决方案1】:

有很多方法可以做到这一点,这取决于您希望控制的位置

最基本的地方就是使用

试一试。

接下来是使用 BaseController 并在那里使用 OnException 方法

另一种方法是使用 MVC 提供的过滤器来处理 GlobalException

下一个方法可能是在 global.asax.cs 中使用 Application_Error,这将是我们可以编写自己的异常逻辑的一个地方

【讨论】:

    【解决方案2】:

    使用try-catch

    try{
    ----code----
    }
    catch(exception ex)
    {
    ---code after exception occurs---
    }
    

    在这里,ex 捕获异常,您也可以检查异常发生的原因

    【讨论】:

      【解决方案3】:

      这是一个示例。 ExceptionMiddleware 负责处理异常。
      当然需要在 Startup.cs 类的 Configure 方法中添加。像这样的:

      app.UseMiddleware<ExceptionMiddleware>();
      
      
       public class ExceptionMiddleware
          {
              private readonly RequestDelegate next;
              private readonly ILogger<ExceptionMiddleware> logger;
              private readonly IHostEnvironment env;
              public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment env)
              {
                  this.env = env;
                  this.logger = logger;
                  this.next = next;
      
      
              }
      
              public async Task InvokeAsync(HttpContext context)
              {
      
                  try 
                  {
                      await next(context);
                  }
                  catch(Exception ex) 
                  {
                    logger.LogError(ex,ex.Message);
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                    var response = env.IsDevelopment() 
                    ? new ApiException((int)HttpStatusCode.InternalServerError, ex.Message, ex.StackTrace.ToString())
                          : new ApiException((int)HttpStatusCode.InternalServerError);
      
                         var options = new JsonSerializerOptions{PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
      
                         var json = JsonSerializer.Serialize(response, options);
      
                         await context.Response.WriteAsync(json);
      
      
      
      
      
      
                  }
              }
          }
       public class ApiResponse
          {
              public ApiResponse(int statusCode, string message = null)
              {
                  StatusCode = statusCode;
                  Message = message ?? GetDefaultMessageForStatusCode(statusCode);
              }
      
              public int StatusCode { get; set; }
              public string Message { get; set; }
      
              private string GetDefaultMessageForStatusCode(int statusCode)
              {
                  return statusCode switch
                  {
                      400 => "A bad request, you have made",
                      401 => "Authorized, you are not",
                      404 => "Resource found, it was not",
                      500 => "Errors are the path to the dark side. Errors lead to anger.  Anger leads to hate.  Hate leads to career change",
                      _ => null
                  };
              }
          }
      
      public class ApiException : ApiResponse
          {
              public ApiException(int statusCode, string message = null, string details = null) : base(statusCode, message)
              {
                  Details = details;
              }
      
              public string Details { get; set; }
          }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多