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