Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OData WebApi 2 Error Handling

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

like image 506
darewreck Avatar asked Dec 09 '15 02:12

darewreck


1 Answers

context.Result = new System.Web.Http.Results.ResponseMessageResult(msg);
like image 149
Tiberiu Avatar answered Oct 13 '22 21:10

Tiberiu