Kestrel服务器在发生异常时崩溃

时间:2020-03-27 12:44:45

标签: c# asp.net-core exception kestrel-http-server

我正在将基于Kestrel的服务器应用程序与ASP.net core 2.1一起使用。我有一个这样的自定义错误处理中间件:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        Log.Warning(exception,"Exception occurred: {exception}",exception);

        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        var result = JsonConvert.SerializeObject(new { error = exception.Message });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;

        return context.Response.WriteAsync(result);
    }
}

这似乎在99%的情况下都有效,但是现在每隔一段时间,然后服务器进程就会停止,并且我看到一些异常作为最后记录的条目。不幸的是,我无法在我的开发机器上复制它,它仅出现在生产系统上。据我了解,无论如何都不会发生这种情况。

我可以使服务器停止运行的任何已知错误吗?我可以启用诊断功能吗?

记录的异常的堆栈跟踪通常表示输入出现问题,或者我想使用ErrorHandlingMiddleware报告的事情。

1 个答案:

答案 0 :(得分:0)

您使用的是Windows还是Liunx?如果使用Windows,则应该能够使用WER(Windows错误报告)https://michaelscodingspot.com/how-to-create-use-and-debug-net-application-crash-dumps-in-2019/#Automatically-create-dump-on-Crash捕获进程崩溃时的崩溃转储。

在Linux上,您可以这样做https://www.cyberciti.biz/tips/linux-core-dumps.html

这应该使您可以收集故障转储,并且可以对其进行分析以查看崩溃的来源。

通常,我们捕获请求期间发生的所有异常。崩溃的过程通常意味着:

  • 从以下位置抛出异常:
    • 代码中的异步void方法
    • 后台线程
  • stackoverflow异常
相关问题