Send error message to user (ASP.NET MVC)

Asked

Viewed 811 times

2

I have the following situation: in my controller MovementsController got an action Details who is responsible for performing a database search through the Id received. The question is: if no data is found in the database how do I direct the user to an error page containing the reason for the error (in case the property Message of the type object Exception)? All I’ve been able to do so far is launch a HttpException for the user to be directed to a custom page NotFound.cshtml, as set out in Web.config.

Action Details:

    // GET: Movements/Details
    public ActionResult Details (int? Id)
    {
        try
        {
            return View(_service.GetById(Id.GetValueOrDefault()));
        }
        catch (ApplicationException e)
        {
            if (e is NotFoundException)
                throw new HttpException();
            else
                return RedirectToAction(nameof(Index));
        }
    } 

Web.config:

<customErrors mode="On" defaultRedirect="~/Errors/Error">
  <error statusCode="404" redirect="~/Errors/NotFound" />
</customErrors>

1 answer

3


You don’t necessarily need an Exception to run the customErrors, you can simply return the Status Code you want:

catch (ApplicationException e) when (e is NotFoundException)
{
     return NotFound();
}
catch (ApplicationException e)
{
     return RedirectToAction(nameof(Index));
}

As there will be a redirect, you would need to store the error message somewhere, I suggest using the TempData:

catch (ApplicationException e) when (e is NotFoundException)
{
     TempData["ErrorMessage"] = e.Message;
     return NotFound();
}

And then use in View of error:

@TempData["ErrorMessage"].ToString()

If you don’t want to store these values, you could also redirect to the error action using the RedirectToAction passing the error message as a parameter.

  • I understood.. however, whenever the method NotFound() is executed the user is directed to a standard IIS error page, even though I have set a custom page on Web.config. However, when I try to access an action that does not exist the server returns me the custom error page.

  • 1

    Vish, I think you won’t be able to use it this way then. You would have to use httpErrors instead of customErrors

  • I adapted Web.config to use httpErrors as well and it worked perfectly, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.