3

I have a situation whereby I need to return an exception to the client in the form of a partial view. Here is my code

            catch(PasswordException ex)
            {
                Response.StatusCode = 500;
                ViewBag.Message = ex.Message;
                return PartialView("Exception");
            }

I'm setting the response statuscode to 500 so the response is caught in the error section of the ajax call.

This works fine but it seems a bit overkill to return a server error just to flag this exception.

Is there a better/standard way of doing this?

heymega
  • 9,215
  • 8
  • 42
  • 61
  • Technically, it's not a server error...The user entered the wrong password, so the error code you should be returning should be 401 (Unauthorized). Note this will also get caught by the client-side Javascript. – saluce Oct 17 '13 at 14:55

2 Answers2

1

Try this,Create Custom error enum and use as below:

/// <summary>
/// Redirect to custom error page.
/// </summary>
/// <returns>View for custom error page.</returns>
public ActionResult Error(CustomError customErrorType,string message)
{
switch (customErrorType)
    {
        case CustomError.A:
            @ViewBag.ErrorMessage = message;
            @ViewBag.Title= CustomError.A;
            break;
        case CustomError.B:
            @ViewBag.ErrorMessage = message;
            @ViewBag.Title= CustomError.B;
            break;          
    }
    return View("_CustomError");
}

View

@{
    @ViewBag.Title
  }

    @ViewBag.ErrorMessage

Redirect as below:

catch(PasswordException ex)
    {
        Response.StatusCode = 500;
        return RedirectToAction(Response.StatusCode,ex.Message);
    }
Amit
  • 15,217
  • 8
  • 46
  • 68
0

You can declare the errors on your web.config:

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

Then you manage it in the ErrorController :

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return PartialView("Error");
    }
    public ViewResult ServerError()
    {
        Response.StatusCode = 500; 
        return PartialView("ServerError");
    }

     public ViewResult NotFound()
    {
        Response.StatusCode = 404; 
        return PartialView("NotFound");
    }
}
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82