I have a method in a controller that looks like this:
[HttpPost]
public void UnfavoriteEvent(int id)
{
try
{
var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID",
new { EventID = id, UserName = User.Identity.Name });
if (rows != 1)
{
Response.StatusCode = 500;
Response.Status = "There was an unknown error updating the database.";
//throw new HttpException(500, "There was an unknown error updating the database.");
}
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Status = ex.Message;
//throw new HttpException(500, ex.Message);
}
}
And as you can see I’ve tried a couple of different ways to throw this error back. In the JavaScript I have the following block to call this method:
var jqXHR;
if (isFavorite) {
jqXHR = $.ajax({
type: 'POST',
url: '/Account/UnfavoriteEvent',
data: { id: $("#EventID").val() }
});
}
else {
jqXHR = $.ajax({
type: 'POST',
url: '/Account/FavoriteEvent',
data: { id: $("#EventID").val() }
});
}
jqXHR.error = function (data) {
$("#ajaxErrorMessage").val(data);
$("#ajaxError").toggle(2000);
};
Now, what I want to do is get the error that occurs thrown back to the jqXHR.error function so that I can handle it properly.
Currently the code that is uncommented throws an exception saying that the text I’m placing in Status is not allowed, and the commented code actually returns the standard error page as the response (not surprising really).
So, I have a couple of questions:
- How do I throw the error properly?
- What does the
Response.Statusproperty do?
Thanks all!
You will be abled to get the response status from the javascript side, doing the following:
As you can see, you must pass the function for
errorto theajaxfunction… in you example, you are setting the function to theerrorproperty ofjqXHRwith no effect at all.Documentation on ajax events
jQuery docs say that the error string will come in the
errorThrownparameter.Do not use Response
Instead, you should return
HttpStatusCodeResult: