【问题标题】:How do I exactly use try-catches for fault handling?我如何准确地使用 try-catch 进行故障处理?
【发布时间】:2021-11-30 10:49:57
【问题描述】:

所以目前我需要实现 try-catch,但无论在哪里,try-catch 都可能是相关的。你如何确定在哪里使用 try-catch?

还有一种通用的方法来实现 try-catch 吗?例如,有什么方法可以在故障处理中使用空类,如下所示?

public class FailedRoleManager : IRoleManager { }

【问题讨论】:

  • Exceptions 是以下问题的答案:检测到错误的代码通常不知道如何处理它。所以它只是传播错误,直到它到达知道如何处理错误的代码。因此,在双方都可能预期异常并知道如何处理它的地方使用try-catch
  • 所以基本上我总是可以在我的 HomeController(..NET Core MVC 应用程序)中使用 try-catch,因为它会调用许多其他代码部分,因此将其置于“最高级别”?跨度>

标签: c# .net-core try-catch try-catch-finally


【解决方案1】:

根据您正在执行的项目类型,可以制作一个中间件来处理应用程序中发生的所有异常。在此链接中,您可以看到在 .net 核心 api 中实现全局错误捕获的示例:

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";
            
            response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var result = JsonSerializer.Serialize(new { message = error?.Message });
            await response.WriteAsync(result);
        }
    }
}

https://jasonwatmore.com/post/2020/10/02/aspnet-core-31-global-error-handler-tutorial#:~:text=The%20global%20error%20handler%20middleware%20is%20used%20catch%20all%20exceptions,Configure%20method%20of%20the%20Startup.

【讨论】:

  • 我如何知道链接中提到的所有可能的异常,如 AppException 和 KeyNotFoundException?
  • 您不需要知道所有可能的异常。您可以简单地捕获异常,并将其视为内部错误。我编辑了答案以添加示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 2013-04-27
相关资源
最近更新 更多