如何从 webmethod 返回错误?

发布于 2024-12-01 20:42:34 字数 422 浏览 1 评论 0原文

如何在用 WebMethod 修饰的 aspx 页面方法中返回错误?

示例代码

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

[WebMethod]
public static string GetData()
{

}

如何从 webmethod 返回错误?因此可以使用 jquery 错误部分来显示错误详细信息。

How does one return an error in an aspx page method decorated with WebMethod?

Sample Code

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

[WebMethod]
public static string GetData()
{

}

How does one return error from a webmethod? So one can be able to use the jquery error portion to show the error detail.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

匿名的好友 2024-12-08 20:42:34

我不知道是否有更特定于 WebMethod 的方法,但在 ASP.NET 中,您通常只需为 响应对象。像这样的事情:

Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;

使用标准错误代码是向消费 HTTP 客户端通知错误的适当方法。在结束响应之前,您还可以 Response.Write() 您想要发送的任何消息。这些格式的标准化程度要低得多,因此您可以创建自己的格式。但只要状态代码准确地反映了响应,那么您的 JavaScript 或使用该服务的任何其他客户端就会理解该错误。

I don't know if there's a more WebMethod-specific way of doing it, but in ASP.NET you'd generally just set the status code for your Response object. Something like this:

Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;

Using standard error codes is the appropriate way to notify a consuming HTTP client of an error. Before ending the response you can also Response.Write() any messages you want to send. The formats for those are much less standardized, so you can create your own. But as long as the status code accurately reflects the response then your JavaScript or any other client consuming that service will understand the error.

氛圍 2024-12-08 20:42:34

只需在 PageMethod 中抛出异常并在 AjaxFailed 中捕获它即可。像这样的东西:

function onAjaxFailed(error){
     alert(error);
}

Just throw the exception in your PageMethod and catch it in AjaxFailed. Something like that:

function onAjaxFailed(error){
     alert(error);
}
兲鉂ぱ嘚淚 2024-12-08 20:42:34

结果页面的 http 状态代码(4xx - 用户请求故障,5xx - 内部服务器故障)指示错误。我不知道asp.net,但我想你必须抛出异常或类似的东西。

An error is indicated by the http status code (4xx - user request fault, 5xx - internal server fault) of the result page. I don't know asp.net, but I guess you have to throw an exception or something like that.

你在看孤独的风景 2024-12-08 20:42:34

JQuery xhr 将在responseText/responseJSON 属性中返回错误和堆栈跟踪。

例如:
C#:

throw new Exception("Error message");

JavaScript:

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxFailed (jqXHR, textStatus, errorThrown) {
    alert(jqXHR.responseJSON.Message);
}

the JQuery xhr will return the error and stack trace in the responseText/responseJSON properties.

For Example:
C#:

throw new Exception("Error message");

Javascript:

$.ajax({
    type: "POST",
    url: "./Default.aspx/GetData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxFailed (jqXHR, textStatus, errorThrown) {
    alert(jqXHR.responseJSON.Message);
}
仅此而已 2024-12-08 20:42:34

我尝试了所有这些解决方案以及其他 StackOverflow 答案:

对我来说没有任何作用。

所以我决定自己手动捕获 [WebMethod] 错误。
看我的例子:

[WebMethod]
public static WebMethodResponse GetData(string param1, string param2)
{
    try
    {
        // You business logic to get data.
        var jsonData = myBusinessService.GetData(param1, param2);
        return new WebMethodResponse { Success = jsonData };
    }
    catch (Exception exc)
    {
        if (exc is ValidationException) // Custom validation exception (like 400)
        {
            return new WebMethodResponse
            { 
                Error = "Please verify your form: " + exc.Message
            };
        }
        else // Internal server error (like 500)
        {
            var errRef = MyLogger.LogError(exc, HttpContext.Current);
            return new WebMethodResponse
            {
                Error = "An error occurred. Please contact your administrator. Error ref: " + errRef
            };
        }
    }
}

public class WebMethodResponse
{
    public string Success { get; set; }
    public string Error { get; set; }
}

I tried all those solutions among with other StackOverflow answers:

Nothing worked for me.

So I decided simply to catch [WebMethod] errors by myself manually.
See my example:

[WebMethod]
public static WebMethodResponse GetData(string param1, string param2)
{
    try
    {
        // You business logic to get data.
        var jsonData = myBusinessService.GetData(param1, param2);
        return new WebMethodResponse { Success = jsonData };
    }
    catch (Exception exc)
    {
        if (exc is ValidationException) // Custom validation exception (like 400)
        {
            return new WebMethodResponse
            { 
                Error = "Please verify your form: " + exc.Message
            };
        }
        else // Internal server error (like 500)
        {
            var errRef = MyLogger.LogError(exc, HttpContext.Current);
            return new WebMethodResponse
            {
                Error = "An error occurred. Please contact your administrator. Error ref: " + errRef
            };
        }
    }
}

public class WebMethodResponse
{
    public string Success { get; set; }
    public string Error { get; set; }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文