If you want to ensure that the api returns the same class even if an error occurs I would use the ExceptionFilters
Create your own implementation of IHttpActionResult
public class FormatErrorResponse : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public Exception exception { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
//Here, create the response you want to be returned when an exception occurs
//Here's my implementation of it where ErrorObj is my custom class which formats the exception the way I want
var response = Request.CreateResponse<ErrorObj>(HttpStatusCode.InternalServerError, ErrorObj.GetError(exception));
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
Then create the filter where you use the FormatErrorResponse class
public class ExceptionProvider : IExceptionHandler
{
public virtual Task HandleAsync(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
if (!ShouldHandle(context))
{
return Task.FromResult(0);
}
return HandleAsyncCore(context, cancellationToken);
}
public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
HandleCore(context);
return Task.FromResult(0);
}
public virtual void HandleCore(ExceptionHandlerContext context)
{
//Use the FormatErrorResponse here
context.Result = new FormatErrorResponse
{
Request = context.ExceptionContext.Request,
exception = context.Exception
};
}
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return context.ExceptionContext.CatchBlock.IsTopLevel;
}
}
Finally, attach the filter to the HttpConfiguration in the WebApiConfig class
config.Services.Replace(typeof(IExceptionHandler), new ExceptionProvider());