I usually use a helper function that deals with exception handling in my Web API projects. I pass the exception that's thrown as an argument to it, then return a HttpResponseException and throw that.
The thrown exception will automatically be serialized to the return type of your Http verb function. In my example I return a Task as it'll serialize any .Net type to a generic object.
If you look at my example below you'll see I have a Method called Get that has its return type set to Task. The object type will be serialized to JSON if the front-end app performs a HTTP GET (in your case a POST) with the Accept header set to 'application/json', when the method returns it'll serialize the return type of Task to json. This also works for the Accept type of text/xml.
I'd recommend filtering specific data in your helper method. you probably don't want people consuming your API to get full stack traces and the like after all, but obviously this is down to your requirements.
public async Task<Object> Get()
{
object result = null;
try
{
result = await methodThatThrowsException();
}
catch (Exception ex)
{
throw CreateHttpResponseException(ex);
}
return result;
}
Helper Method
private HttpResponseException CreateHttpResponseException(Exception ex)
{
HttpResponseMessage message;
if (ex.GetType() == typeof(FaultException<LoginFault>))
{
message = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
else
{
message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
message.Content = new StringContent(ex.Message);
return new HttpResponseException(message);
}
In the helper Method, use a StringBuilder to build up what you want to display in your front end. Concatenate and format your error message as you require and then assign the string value to your MessageResponseMessage.Content field.
You'll need to iterate over the Exception InnerException and check to see if it's null, concatenating the exception message etc... as you need.
You could iterate over inner Exceptions using something like
StringBuilder exceptionMessage = new StringBuilder();
Exception inner = ex.InnerException;
while (inner != null)
{
exceptionMessage.Append(inner.Message)
.Append(Environment.NewLine);
inner = inner.InnerException;
}