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?

1
  • 2
    Returning JSON implies that the call could be part of an data API, should you redirect to a webpage for that? Commented Apr 26, 2016 at 12:23

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

And this will run automatically when a error rises? Will this work for example when a Insert with entity framework fails?
This method catches all unhandled ASP.NET errors (all the errors that are not handled by Try/Catch block) while processing a request.
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");
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.