4

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オブジェクトで、そこにエラーがあると想定しますか?

不明な点がありましたらお知らせください。

4

1 に答える 1

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;
        }
    });
于 2013-05-28T15:17:12.680 に答える