You can create your own result that includes whatever content you want:
public class ServerErrorResult : HttpActionErrorResult
{
public Exception Exception {get; set;}
public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var content = Content;
if(Exception != null)
{
content += $"\r\nException Details:{Exception.Message}";
}
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(content),
RequestMessage = Request;
};
return Task.FromResult(response);
}
}
Then in your controller, you just return this new result instead:
public IHttpActionResult GetSomething()
{
try
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(GetContent(...));
return ResponseMessage(result);
}
catch (Exception ex)
{
return new ServerErrorResult
{
Exception = ex
};
}
}
You can also create an extension method on the controller to abstract some of this plumbing away:
public static HttpActionErrorResult ServerError(this ApiController controller, Exception ex)
{
return new ServerErrorResult
{
Exception = ex
};
}
And call it from your controller like this:
public IHttpActionResult GetSomething()
{
try
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(GetContent(...));
return ResponseMessage(result);
}
catch (Exception ex)
{
return ServerError(ex);
}
}
Hope that helps.