Error Handling for the ASP.NET Odata API

I am interested in knowing what recommendations are used to raise exceptions in ODataController.

If you throw an exception in a method, it is translated into the default 500 response code, and the content contains information about the error. I would like to explicitly specify a response code and send 400 in case of an invalid key.

For example: if the input request has an invalid key, he would like to return the HttpResponseCode 400 code, and the contents should contain error information similar to throwing an exception.

Thanks so much for your inputs.

+6
source share
2 answers

OData (at least since v3) uses specific json to represent errors:

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

Microsoft.Net contains Microsoft.Data.OData.ODataError and Microsoft.Data.OData.ODataInnerError to generate an OData error on the server side.

To generate the correct OData error response ( HttpResponseMessage ), which contains error information that you can:

1) generate and return the HttpResponseMessage to the controller action using System.Web.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse method

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

2) throw an HttpResponseException using the same method to create an HttpResponseMessage

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

3) throw an arbitrary typed exception and convert it using Web Api action filters

 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); } } 
+13
source

Use HttpResponseException ,
e.g. throw new HttpResponseException(HttpStatusCode.NotFound); .
Details can be found here .

+1
source

Source: https://habr.com/ru/post/956009/


All Articles