Muflix
Muflix

Reputation: 6768

Error handling in the controller

I have this two controllers actions

#1 will throw divide by zero exception

public IActionResult About()
{
     ViewData["Message"] = "Your application description page.";
     var x = 0;
     var y = 5 / x;
     return View();
}

#2 after the exception, i want this action to be called in production mode.

public IActionResult Error()
{
    var model = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };
    return View(model);
}

I have two issues

  1. When I am in VS Debug mode, app.UseDeveloperExceptionPage() is used and therefore Error controller is not called (that is fine for development environment).
  2. When I am in VS Production mode, visually app.UseDeveloperExceptionPage() is used but i dont know how to confirm what environment is really used (breakpoints in startup.cs does not work in production mode.)
  3. If somehow Error action was called, how can I get full exception message (for log purpose) ? By default only RequestId is stored inside the model.

I do not want to use try catch syntax in each action or repeat action filter attribute, because i want to have general exception handler implemented like i had before in global.asax before core version.

My startup.cs is very easy.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseStatusCodePages();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

any idea ?

Upvotes: 0

Views: 206

Answers (2)

Pooja Suryawanshi
Pooja Suryawanshi

Reputation: 341

we can use the below line of code

 var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
           var error = feature?.Error;
            _logger.LogError("Oops!", error);
            return View("~/Views/Shared/Error.cshtml", error);

Can you refer the below link for more details Click

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239220

To get the exception details, you just need:

var ex = HttpContext.Features.Get<IExceptionHandlerFeature>();

Upvotes: 1

Related Questions