2013-08-15 2 views
7

このコードでは、Microsoft Web APIのHttpスタックとjQueryを使用しています。Web APIからjQuery.ajaxにカスタムエラーメッセージを取得するにはどうすればいいですか?

は、どのように私はjQueryのdeferred.fail()で表示CreateErrorResponse()からHttpErrorパラメータによって作成されたカスタムエラーメッセージを得るのですか?

ApiControllerでテスト目的のためにエラー応答を作成する例:

public HttpResponseMessage Post(Region region) 
{ 
    var error = new HttpError("Failure to lunch."); 
    return this.Request.CreateErrorResponse(
       HttpStatusCode.InternalServerError, 
       error); 
} 

はここで、表示するエラーメッセージを見つけるためにしようとしているカットダウン、クライアントの「昼食に失敗。」。

$.ajax({ 
    type: 'POST', 
    url: 'api/region', 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify(region) 
}) 
.fail(function (jqXhr, textStatus, errorThrown) { 
    alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText); 
}); 

何が表示されますことは次のとおりです。

"error: Internal Server Error: {full stack here}"

私が代わりに欲しいです:

"Failure to lunch."

+0

「fa」を意味しますか打ち上げるilure "not lunch –

+3

@KevinHolditch私は空腹だった! – Boggin

+1

私は今あなたの質問を読んだ:) –

答えて

6

あなたはresponseText文字列を解析して、Messageプロパティを使用できます。

.fail(function (jqXhr, textStatus, errorThrown) { 
    if (jqXhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) { 
     // only parse the response if you know it is JSON 
     var error = $.parseJSON(jqXhr.responseText); 
     alert(error.Message); 
    } else { 
     alert('Fatal error'); 
    } 
}); 
+0

これは私が混乱しているところです。 jqXhr.responseText.Messageには、HttpErrorに挿入したカスタムメッセージではなく、InternalServerError( "エラーが発生しました。")のエラーメッセージがあります。 – Boggin

+0

私は私の答えで間違いを犯しました。 'alert(error).Message'の代わりに' alert(error.Message) 'を使うべきです。 Messageプロパティには、 'Failure to lunch.'というテキストが含まれます。私はちょうどそれをテストし、それは正常に働いた。 'jqXhr.responseText'の値を表示できますか? –

+0

私のテストケースは、CreateErrorResponseコードがヒットしてしまう前に返されていた別のInternalServerError例外をスローしていたので、私は混乱しました。 Web APIは、try..catchコードが存在しなければ、これにうまく対処します。あなたは大丈夫です、メッセージのプロパティは私が必要なものです。 – Boggin

関連する問題