Flats
Flats

Reputation: 81

how to create a request when an exception is caught in ASP.NET Core app

I would like to, upon catching an exception in my code, redirect the user to an error page of my own design. As of right now, the application eats the exception and runs anyway.

I have an ErrorController.cs containing:

public class ErrorController : Controller
{
    public IActionResult MyError()
    {
        return View();
    }
}

as well as an error page MyError.cshtml:

@{
    ViewData["Title"] = "MyError";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

<h3>Development Mode</h3>
<p>
    Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
    <strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>

My issue involves me not being aware how to get the browser that I am using to view my app in to redirect to this error page mysite.com/Error/MyError

In my understanding I need to make a request to /Error/MyError and then the controller would open the .cshtml page. I need to do this in the case that I catch an exception elsewhere (not in a controller) in my program.

What is the best practice for this, or honestly, any way to do this at all?

NOTE: I am looking for a solution in the case that the exception thrown does not have an HTTP status code. one of the exceptions thrown is a Microsoft.Data.SqlClient.SqlException I have seen some documentation on how to display a custom error page for specific status codes using web.config, but I don't think that this is going to work in this situation. (Please correct me if I am wrong)

Upvotes: 0

Views: 408

Answers (2)

LLL
LLL

Reputation: 3771

From ASP.NET docks here. Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/error");
    }

    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

[ApiController]
public class ErrorController : ControllerBase
{
    [Route("/error")]
    public IActionResult Error() => Problem();
}

Haven't tried it, but I don't see why

[ApiController]
public class ErrorController : ControllerBase
{
    [Route("/error")]
    public IActionResult Error() => View();
}

wouldn't work.

Upvotes: 1

taylorswiftfan
taylorswiftfan

Reputation: 1517

I think you need to provide the redirection in the catch of a try catch clause. i.e.

    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        try
        {
            throw new Exception(); // Do something here that can throw an Exception, but I have purposely thrown an Exception here so that it jumps into the catch

            return View();
        }
        catch (Exception ex)
        {
            return RedirectToAction("Error", "MyError");
        }
    }

Upvotes: 0

Related Questions