0

I have read many articles now about how to handle errors in asp.net, and I think it is a lot of information to take in.

I'm using service layer pattern, and in my service model, I have the following code:

   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();
        }    
    }

If a problem rises, I want to redirect the user to a error page that says something went wrong.

I call my service method from my controller:

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

How can I determine in my controller method if something went wrong in the service, and then redirect the user to the error page?

Or should I have a global errorHandler that transfer the user as soon a excetion is caught?

halfer
  • 19,824
  • 17
  • 99
  • 186
Bryan
  • 3,421
  • 8
  • 37
  • 77

2 Answers2

1

You can add Application_Error method in global.asax. For example:

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");
}
rba
  • 338
  • 2
  • 11
  • And this will run automatically when a error rises? Will this work for example when a Insert with entity framework fails? – Bryan Apr 26 '16 at 12:26
  • This method catches all unhandled ASP.NET errors (all the errors that are not handled by Try/Catch block) while processing a request. – rba Apr 26 '16 at 12:36
0

We've tried multiple things, but what seems to work best is to just handle every exception yourself. We didn't completely invent this yourself, the inspiration was from here:
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");
        }
    }
Community
  • 1
  • 1
Remy
  • 12,555
  • 14
  • 64
  • 104