OData WebApi 2 Error Handling
Asked Answered
T

1

6

In my web service, I override the ExceptionHandler, but it's not clear to me how you would format the exception to fit the OData Error standard. Perhaps i'm approaching it wrong since I can't find any examples online.

From my understanding, with web api 2 there is a concept of global exception handling where you use a custom ExceptionHandler to handle any exceptions thrown in the service. The Exception is still expected to update the ExceptionContext.Result with a new IHttpActionResult(). How do you format the data you input into IHttpActionResult to format to OData Error.

Below is a snippet of the ExceptionHandler, and I'm stuck on how you would override the context.Result with the correct OData HttpResponse message.

public class CustomExceptionHandler: ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        HttpResponseMessage msg = context.Request.CreateErrorResponse(HttpStatusCode.NotFound, new ODataError
        {
            ErrorCode = context.Exception.Message,
            Message = context.Exception.InnerException.Message,
            InnerError = new ODataInnerError
            {
                Message = context.Exception.InnerException.Message
            }
        });
        context.Result = //How do you wrap the OData HttpResponseMessage into a IHttpActionResult

    }


}

Any Advice Appreciated, Thanks, D

Timely answered 9/12, 2015 at 2:29 Comment(2)
were you able to find any solution for this? Any tips are appreciated. ThanksCarolann
sorry, I haven't gotten back to figuring this. When i do, I'll update this.Timely
H
1
context.Result = new System.Web.Http.Results.ResponseMessageResult(msg);
Hygroscopic answered 29/9, 2017 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.