我有一个控制器中的方法如下:
[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);
}
}
正如您所见,我已经尝试了几种不同的方法来抛出此错误。在JavaScript代码中,我有以下块来调用此方法:
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);
};
现在,我想要做的是将发生的错误抛回到
jqXHR.error
函数中,以便我可以正确处理它。目前未注释的代码会抛出异常,说明我放置在
Status
中的文本不被允许,而已注释的代码实际上返回标准错误页面作为响应(这并不奇怪)。所以,我有几个问题:
- 如何正确地抛出错误?
Response.Status
属性是什么作用?