Search code examples
asp.netexceptionasp.net-web-apierror-handlingodata

How to catch or intercept ODataException to return custom error payload


I am refactoring an ASP.NET WEB API solution that uses Odata. When dealing with errors I would like to provide a custom error payload which is defined in my CustomException class.

The issue is that when I make a bad request the generated response is the ODataException error payload which contains some confidential information that I don't want exposed and also the stack trace.

I need to modify this Odata payload and replace it with my own.

So far what I've tried is to use Exception Filters applied on Controller level and also tried to register an Exception Handler on global level. None of these worked.

Any help would be greatly appreciated.


Solution

  • I was able to resolve it with Exception Filter, I was using the wrong method before:

    public class CustomExceptionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {    
            ErrorContentResponse error = new ErrorContentResponse();
    
            var response = new HttpResponseMessage(actionExecutedContext.Response.StatusCode)
            {
                Content = new ObjectContent<ErrorContentResponse>(error, new JsonMediaTypeFormatter())
            };
    
            actionExecutedContext.Response = response;
        }
    }