如何返回自定义异常消息,Ajax调用? [英] How to return custom exception message to Ajax call?

查看:290
本文介绍了如何返回自定义异常消息,Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个Ajax请求的错误返回特定的信息。

I want to return a specific message on error of an ajax request.

[WebMethod]
public static AjaxReturnObject SubmitWager(string token, string track, string race, string amount, string pool, string runners)
{
    try
    {
        var serviceReturn = Services.Account.SubmitWager("", track, race, pool, amount, runners);
        return new AjaxReturnObject(serviceReturn.AccountToken, serviceReturn.Payload);
    }
    catch (CustomServiceException<string> e)
    {
        throw new Exception(e.Message);
    }
}

调试说,它击中我抓时,我需要它,但是当我看到内XHR我的jQuery AJAX调用它总是说有一个错误处理请求。

Debugging says that it hits my catch when I need it to, but when I look at the xhr within my jquery ajax call it ALWAYS says "There was an error processing the request."

error: function (xhr, textStatus, errorThrown) {
            log(xhr, textStatus, errorThrown);
}

如何才能让我的期望的消息,复出xhr.responseText下Ajax调用?

How can I get my desired message to comeback to the ajax call under xhr.responseText?

推荐答案

也许更好的路线将是定义与code中的AJAX请求,检查一个成功标志的成功回调:

Perhaps the better route would be is to define the success callback of the AJAX request with code that checks a success flag:

C#

[WebMethod]
public static AjaxReturnObject SubmitWager(string token, string track, string race,   string amount, string pool, string runners)
{
try
{
    var serviceReturn = Services.Account.SubmitWager("", track, race, pool, amount, runners);
    return new AjaxReturnObject(serviceReturn.AccountToken, serviceReturn.Payload);
}
catch (CustomServiceException<string> e)
{
    return new AjaxReturnObject(0, e.Message();
}
}


的JavaScript

$.ajax({
  ...
  success: function (data) {
    if (data.AccountToken == 0) {
      // There was an error 
      log(data.Payload);
    }
    else {
      // your code
    }
  }
});

我提供这样的选择,因为我不知道,如果你抛出一个错误,在服务器端code,该函数返回任何东西。您收到,该错误客户端,错误回调真的是指请求是否可以作出。

I offer this alternative because I'm not sure that if you throw an error in the server side code, that the function returns anything back. That error you're receiving, is client side, the error callback really refers to whether or not the request could be made.

这篇关于如何返回自定义异常消息,Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆