为jquery.ajax()生成自定义错误

时间:2013-02-07 08:30:24

标签: c# jquery asp.net ajax

让我们假设我的httphandler(.ashx)中有以下方法:

private void Foo()
{
    try
    {
        throw new Exception("blah");
    }
    catch(Exception e)
    {
        HttpContext.Current.Response.Write(
            serializer.Serialize(new AjaxError(e)));
    }
}

[Serializable]
public class AjaxError
{
    public string Message { get; set; }
    public string InnerException { get; set; }
    public string StackTrace { get; set; }

    public AjaxError(Exception e)
    {
        if (e != null)
        {
            this.Message = e.Message;
            this.StackTrace = e.StackTrace;
            this.InnerException = e.InnerException != null ? 
                e.InnerException.Message : null;


            HttpContext.Current.Response.StatusDescription = "CustomError";
        }

    }
}

当我对该方法进行$.ajax()调用时,我会在success回调中结束,无论后端出现什么问题,我最终都会进入catch

我已经扩展了ajax方法以规范化错误处理,因此无论是“jquery”错误(解析错误等)还是我的自定义错误,我都会在错误回调中结束。

现在,我想知道的是,我应该添加类似

的内容
HttpContext.Current.Response.StatusCode = 500;

以jQuerys错误处理程序结束,或者我应该处理

HttpContext.Current.Response.StatusDescription = "CustomError";

在jqXHR对象上,并假设它出现错误?

如果不清楚,请告诉我。

1 个答案:

答案 0 :(得分:0)

您至少需要使用状态代码,因为$ .ajax可以像这样实现失败函数:

$.ajax({...})
    .fail(function(xhr) {
        console.log(xhr.statusText); // the status text
        console.log(xhr.statusCode); // the status code
    });

如果您想直接向用户发送文本,可以使用statusText。如果需要,您还可以为不同的错误执行不同的状态代码(即使状态代码不是常规代码),如下所示:

$.ajax({...})
    .fail(function(xhr) {
        switch(xhr.statusCode) {
            case 401:
                // ... do something
                break;
            case 402:
                // ... do something
                break;
            case 403:
                // ... do something
                break;
        }
    });
相关问题