2016-04-26 101 views
0

我已經閱讀了很多關於如何處理asp.net中的錯誤的文章,並且我認爲這是很多需要輸入的信息。在我的asp.net mvc應用程序中處理錯誤

使用IM服務層圖案,並在我的服務模式

,我有以下代碼:

public List<SpotifyAlbumModel> AddSpotifyAlbums(List<SpotifyAlbumModel> albums) 
    { 
     try 
     { 
      if(albums != null) 
      { 
       ctx.SpotifyAlbums.AddRange(albums); 
       ctx.SaveChanges(); 
      } 

      return albums; 
     } 
     catch(Exception e) 
     { 
      throw new Exception(); 
     }  
    } 

如果問題上升,我想將用戶重定向到一個錯誤頁面,說出事了。

我打電話給我的服務方法,從我的控制器:

public ActionResult AddSpotifyAlbums(List<SpotifyAlbumModel> albums) 
    { 
     _profileService.AddSpotifyAlbums(albums); 
     return Json(new { data = albums }); 
    } 

我怎麼能確定我的控制器方法,如果出事了在服務上,然後將用戶重定向到錯誤頁面?

或者我應該有一個全局errorHandler,儘快發送一個excetion被捕獲?

+2

返回JSON意味着該調用可能是數據API的一部分,如果您重定向到該網頁? –

回答

0

我們已經嘗試過多種方法,但最好的做法是自己處理每個異常。我們完全沒這個發明自己的靈感是從這裏:
ASP.NET MVC 404 Error Handling

protected void Application_EndRequest() 
    {    
     if (Context.Response.StatusCode == 404) 
     { 
      Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url); 

      Response.Clear(); 

      string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name); 

      var rd = new RouteData(); 
      //rd.DataTokens["area"] = "AreaName"; // In case controller is in another area 
      rd.Values["languageCode"] = language; 
      rd.Values["controller"] = "Error404"; 
      rd.Values["action"] = "Index"; 

      Response.TrySkipIisCustomErrors = true; 

      IController c = new Controllers.Error404Controller(); 
      c.Execute(new RequestContext(new HttpContextWrapper(Context), rd)); 
     } 
     else if (Context.Response.StatusCode == 500) 
     { 
      Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url); 

      Response.Clear(); 

      string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name); 

      Response.Redirect("~/" + language + "/error"); 
     } 
    } 
1

可以在Global.asax的添加的Application_Error方法。例如:

void Application_Error(Object sender, EventArgs e) 
{ 
    var exception = Server.GetLastError(); 
    if (exception == null) {   
     return; 
    } 

    // Handle an exception here... 

    // Redirect to an error page 
    Response.Redirect("Error"); 
} 
+0

這會在錯誤升高時自動運行嗎?例如,當插入與實體框架失敗時,這會工作嗎? – Bryan

+0

此方法在處理請求時捕獲所有未處理的ASP.NET錯誤(Try/Catch塊未處理的所有錯誤)。 – rba