MVC 中的异常处理 [关闭]

Posted

技术标签:

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

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

【问题讨论】:

这能回答你的问题吗? Error Handling in ASP.NET MVC 【参考方案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 JsonSerializerOptionsPropertyNamingPolicy = 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; 
    

【讨论】:

以上是关于MVC 中的异常处理 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

控制器中的异常处理 (ASP.NET MVC)

Asp.net MVC 之异常处理

ASP.NET MVC 处理区域中的请求验证异常

NET MVC异常处理模块

Spring MVC异常处理

处理异常时.Net中的常见编程错误? [关闭]