2013-10-15 38 views
6

ODataControllerで例外を発生させるためのベストプラクティスを知りたいと思っています。ASP.NET Odata Web APIのエラー処理

このメソッドで例外を発生させると、デフォルトで応答コード500に変換され、その内容にはエラーの詳細が含まれます。私は応答コードを明示し、無効なキーの場合に400を送信したいと思います。

たとえば、入力要求に無効なキーが含まれていると、HttpResponseCodeを400に戻したい場合、コンテンツに例外の発生と同様のエラーの詳細が含まれている必要があります。ご入力の

どうもありがとう

+0

キーを上げる必要があります見つからないWeb APIをアクションフィルタを使用して、それを変換する404 – qujck

答えて

1

使用HttpResponseException
例えばthrow new HttpResponseException(HttpStatusCode.NotFound);
詳細はhereです。

13

のOData(少なくともV3以降)エラーを表すためにspecific jsonを使用:

{ 
    "error": { 
     "code": "A custom error code", 
     "message": { 
      "lang": "en-us", 
      "value": "A custom long message for the user." 
     }, 
     "innererror": { 
      "trace": [...], 
      "context": {...} 
     } 
    } 
} 

のMicrosoft .NETは、サーバ側でのODataエラーを形成するMicrosoft.Data.OData.ODataErrorMicrosoft.Data.OData.ODataInnerErrorクラスが含ま。 )

1形とSystem.Web.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse方法

return Request.CreateErrorResponse(HttpStatusCode.Conflict, new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." })); 

2を使用して、コントローラのアクションでHttpResponseMessageを返す)を使用してHttpResponseExceptionを投げる:

することができますエラーの詳細が含まれている適切なODataのエラー応答(HttpResponseMessage)を形成するために、 HttpResponseMessageを作成するための同じメソッド

throw new HttpResponseException(
    Request.CreateErrorResponse(HttpStatusCode.NotFound, new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." })); 

3)カスタム型付き例外をスローするそして

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     if (context.Exception is CustomException) 
     { 
      var e = (CustomException)context.Exception; 

      var response = context.Request.CreateErrorResponse(e.StatusCode, new ODataError 
      { 
       ErrorCode = e.StatusCodeString, 
       Message = e.Message, 
       MessageLanguage = e.MessageLanguage 
      }); 
      context.Response = response; 
     } 
     else 
      base.OnException(context); 
    } 
} 
+0

'CreateODataErrorResponse'拡張メソッドと我々はそれが使用する必要がありますの使用は何ですか? – Rahul

関連する問題