4

i see that i get a big html text when i return a HttpException() from an ajax call.

if i do something like this in my controller:

   if (errors.Count > 0)
        {
            throw new HttpException(404, "This is my custom error msg");
        }

i want a nice simple way to parse out that Error Message on the javascript side. Right now when i look at the callback on the client side with something like this

  function decodeErrorMessage(jqXHR, textStatus, errorThrown) {

i see that jqxHR = "3", textStatus = a very long html doc (with a a call stack and error message and errorThrown is "error"

what is the best way to simply pass back and show an error from an http exception?

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • @AVD - I am not requesting a web page, i am doing an ajax post and an exception is thrown and i want to handle it – leora Jan 23 '12 at 03:23
  • Please read this thread - http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages – KV Prajapati Jan 23 '12 at 03:31

1 Answers1

5

Instead of throwing the exception in the controller, catch it and set the response code for the AJAX response:

View logic setup with JQuery:

    $("#btnRefresh").live("click", function(e) {
        $.ajax({
            type: "POST",
            url: '@Href("~/Home/Refresh")',
            data: "reportId=@Model.Id"
        })
        .done(function(message) {
            alert(message);
        })
        .fail(function(serverResponse) {
            alert("Error occurred while processing request: " + serverResponse.responseText);
        });

        e.preventDefault();
    });

Then in your Controller code you catch the exception instead of throwing it:

    [HttpPost, VerifyReportAccess]
    public ActionResult Refresh(Guid reportId)
    {
        string message;

        try
        {
            message = _publisher.RequestRefresh(reportId);
        }
        catch(Exception ex)
        {
            HttpContext.Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            message = ex.Message;
        }

        return Json(message);
    }
tawman
  • 2,478
  • 1
  • 15
  • 24