在Exception解雇后,它需要发送Ajax错误

时间:2017-04-06 05:25:15

标签: jquery ajax asp.net-mvc asp.net-mvc-5

我有一个Ajax方法,当我捕获控制器端异常时。我想将该异常传递给Ajax Error方法。 在这里,在异常解雇后它没有做任何事情。

Ajax Call

function ConNews(){
    $.ajax({
        url: $("#getnewsdtl").val(),
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(newsModelLists),
        dataType: "json",
        success: function (news) {
// some code here.
},
 error: function (jqXHR, textStatus, errorThrown) 
{

// I want get controller catched exception here.
}

});

控制器

[HttpPost]
public string GetNews(List<NewsModel> newsModelList)
{
try
{
      return JsonConvert.SerializeObject(newsModelList);
}
catch (Exception ex)
{

  return  JsonConvert.SerializeObject("adf"); // I want to send thisone to Ajax error function
}
}

2 个答案:

答案 0 :(得分:0)

你可以做的就是创建一个响应模型,如下所示

public class ResponseResult
{
    public bool Success { get; set; }
    public object Data { get; set; }
    public string Message { get; set; }
}

在您的控制器中绑定此模型,如下所示

[HttpPost]
public JsonResult GetNews(List<NewsModel> newsModelList)
{
  ResponseResult result = new ResponseResult();
  try
  {
        result.Data = //Some Data
        result.Success = true;
        result.Message = "Everything Works Fine!!!";
        return JsonConvert.SerializeObject(result);
  }
  catch (Exception ex)
  {
    //Set Success = false as there is an exception as well as you can pass a message 
    result.Message = "Somethinng Goes Wrong!!!";
    result.Success = false;
    return  JsonConvert.SerializeObject(result);
  }
}

Ajax Call

function ConNews(){
    $.ajax({
        url: $("#getnewsdtl").val(),
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(newsModelLists),
        dataType: "json",
        success: function (result) {
         //check here if result.Success is true or false and than some additional work you can done here
         console.log(result);
        },
         error: function (jqXHR, textStatus, errorThrown) 
        {
        // You will not get exception here because your Ajax call has been called without any errors if it fails in case of 404 or something wrong in your ajax requeste than you will get exception here
        // I want get controller catched exception here.
        }
});

答案 1 :(得分:-1)

根据评论中提到的,您在catch块中发送了有效数据。因此,请尝试ajax.complete,添加bool以检查是否发生异常

var checkIfException = false;
function ConNews(){
    $.ajax({
        url: $("#getFlightPriceIteration").val(),
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(ticketModelLists),
        dataType: "json",
        success: function (data) {
        checkIfException = true; //setting true
// some code here.
},
 error: function (jqXHR, textStatus, errorThrown) 
{

// I want get controller catched exception here.
},
 complete: function(){
            if(!checkIfException){
                 alert('Exception occur');
            }
        }

});