2016-04-26 81 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