2014-12-05 60 views
0

我試圖學習和理解Web API 2中的全局異常處理。當我通過下面的代碼步驟時,我想我會在Handle方法中打斷點,但是我不'噸。全局處理Web API中的異常2

我錯過了什麼?

這裏是我做了什麼:我在Visual Studio 2013中創建一個新的Web API項目更新4.在我的根,我創建了下面的類 - 名爲GlobalExceptionHandler.cs,看起來像這樣:

using System.Net.Http; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Web.Http; 
using System.Web.Http.ExceptionHandling; 

public class GlobalExceptionHandler : ExceptionHandler 
{ 
    public override void Handle(ExceptionHandlerContext context) 
    { 

     // --> Break Point in the next line <-- 
     string str1 = context.Exception.Message; 
    } 
} 

這是我Startup.cs是什麼樣子:

using Owin; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Http.ExceptionHandling; 

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
    var config = new HttpConfiguration(); 

    config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 

    config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
    ); 

     app.UseWebApi(config); 
    } 
} 

當我嘗試生成在我的web API方法例外,我期待打在GlobalExceptionHandler handle方法,但我不是。

public IHttpActionResult Get() 
{ 
    throw new HttpResponseException(HttpStatusCode.BadRequest); 
    return Ok("I should not get here because of exception"); 
} 

回答

0

在WebApi中,引發HttpResponseException被認爲返回響應。它不被視爲未處理的異常,因此不會被您註冊的異常處理程序拾取。嘗試拋出另一個異常類型,它應該工作。