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

darewreck
  • 2,576
  • 5
  • 42
  • 67

1 Answers1

1
context.Result = new System.Web.Http.Results.ResponseMessageResult(msg);
slfan
  • 8,950
  • 115
  • 65
  • 78
Tiberiu
  • 46
  • 3