2
\$\begingroup\$

I'm learning ASP.NET Core with MVC pattern and I didn't find anything useful related to this argument.

Actually I'm looking for a way to handle all the application errors inside a single View. The first thing that I did was create the View for display the error, this is the design (pretty simple though):

<h2>@(ViewBag.ErrorMessage == null ? "An error happened" : "" + @ViewBag.ErrorMessage + "")</h2>

and this is the Error controller:

public class ErrorController : Controller
{
    [HttpGet]
    public IActionResult Index(string errorMessage)
    {
        ViewBag.ErrorMessage = errorMessage;
        return View();
    }
}

Essentially, I used the ViewBag for valorize a property called ErrorMessage which contains the parameter errorMessage.

Let me show an example of this logic for the email confirmation:

public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
    if (userId == null || token == null)
    {
        return RedirectToAction("Index", "Error");
    }

    var user = await _userManager.FindByIdAsync(userId);

    if (user != null)
    {
       if (user.EmailConfirmed)
       { 
            return RedirectToAction("Index", "Error", new { errorMessage = "Email already confirmed" });
       }

       IdentityResult result;

       try
       {
           result = await _userManager.ConfirmEmailAsync(user, token);
       }
       catch (InvalidOperationException ex)
       {
           return RedirectToAction("Index", "Error", new { errorMessage = ex.Message });
       }

       if (result.Succeeded)
       {
           //TODO: Send another email
           return View("ConfirmEmail", user);
       }
    }

    return RedirectToAction("Index", "Error", new { errorMessage = "Utser not found" });
    }

Now, I'm not an expert yet of ASP.NET Core so I don't know if my practice is good enough for a production environment, someone could maybe propose a better way or improve my solution?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

While I see no problem design-like or code-like, in the point of view of the user, It can be frustrating.

I guess the method ConfirmEmail is called from a form.

So, imagine how frustrating it is if you fill a form and if there is any error in this form, it redirects you to the Error View ?

Imo, Error display should be handled by Javascript/Html/Css on the same page which thrown the error to avoid losing any data from user's pov. Like, displaying a notification or even an error message below the field.

How you display the error should be specific of the error.

\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.