2016-02-11 51 views
0

我有一些中間件寫在回調中檢查響應是否是500.如果是500我想返回拋出的異常。如何獲取應用程序中引發的異常?獲取早期在應用程序c#中拋出的異常?

Startup.cs

... 
app.UseMiddleware<APIExceptionMiddleware>(); 

// Add MVC to the request pipeline. 
app.UseMvc(); 
... 

APIExceptionMiddleware.cs:

public class APIExceptionMiddleware 
    { 
     private readonly RequestDelegate _next; 

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

     public async Task Invoke(HttpContext context) 
     { 
      context.Response.OnStarting(
       callback: (state) => 
       { 
        HttpResponse response = (HttpResponse)state; 
        if (response.StatusCode == 500) 
        { 
         // want to grab exception here turn it into JSON response place it in the response.Body but not sure how I access the exception. 
         return response.WriteAsync("An Error Occured"); 
        } 
        return Task.FromResult<object>(null); 
       }, state: context.Response); 


      await _next.Invoke(context); 
     } 
    } 

因此,作爲請求進入UseMvc()我有一個拋出的異常。我可以使用app.UseDeveloperException();並用stacktrace和exception獲得一個友好的HTML頁面。

我想幾乎重複一遍,但使它成爲我的應用程序的友好JSON API響應。所以,如果一個500被拋出,我正在使用中間件,我將把它變成一個漂亮的json響應,並通過api請求將其作爲響應發送出去。我的問題是如何在中間件中獲取此異常?

如果UseDeveloperException()正在做,它不應該我能夠嗎?

+0

context.Error? – pnm

+0

有沒有context.Error – allencoded

+0

你的意思是沒有暴露的財產或它是空的? – pnm

回答

1

查看DeveloperExceptionPageMiddleware的代碼...特別看看Invoke(HttpContext context)(如下所示)。不要使用您正在添加的默認中間件,而要使用您自己開始的中間件。它將非常像DeveloperExceptionPageMiddleware:捕獲任何異常,但不是返回錯誤頁面,而是根據需要格式化JSON響應。

public async Task Invoke(HttpContext context) 
{ 
    try 
    { 
     await _next(context); 
    } 
    catch (Exception ex) 
    { 
     _logger.LogError(0, ex, "An unhandled exception has occurred while executing the request"); 

     if (context.Response.HasStarted) 
     { 
      _logger.LogWarning("The response has already started, the error page middleware will not be executed."); 
      throw; 
     } 

     try 
     { 
      context.Response.Clear(); 
      context.Response.StatusCode = 500; 

      await DisplayException(context, ex); 

      if (_diagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.UnhandledException")) 
      { 
       _diagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.UnhandledException", new { httpContext = context, exception = ex }); 
      } 

      return; 
     } 
     catch (Exception ex2) 
     { 
      // If there's a Exception while generating the error page, re-throw the original exception. 
      _logger.LogError(0, ex2, "An exception was thrown attempting to display the error page."); 
     } 
     throw; 
    } 
} 
+0

這正是我一直在尋找的。 – allencoded

+0

請記住,泄漏有關您的系統的信息是一種安全風險 – jltrem

+0

是的,我有一定的幾個我想通過不是所有的人。我會用一個決定來通過那些我想忽略別人的決定。謝謝! – allencoded

相關問題