Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Last active December 22, 2015 19:29
Show Gist options
  • Save danielmackay/6519627 to your computer and use it in GitHub Desktop.
Save danielmackay/6519627 to your computer and use it in GitHub Desktop.
Wrap function with Web API logging. #webapi
protected HttpResponseMessage Wrap<T>(Func<T> func)
{
try
{
var req = HttpContext.Current.Request;
Log.InfoFormat("Service: {0}", req.Path);
if (Log.IsDebugEnabled)
{
req.InputStream.Position = 0;
using (var reader = new StreamReader(req.InputStream))
{
string requestFromPost = reader.ReadToEnd();
Log.DebugFormat("Request: {0}", requestFromPost);
}
}
var result = func();
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (ApplicationException ex)
{
Log.Warn("Validation error " + ex.Message);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
catch (DbUpdateException ex)
{
Log.Error("DB Error", ex);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.GetBaseException().Message);
}
catch (Exception ex)
{
Log.Error("API Error", ex);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.GetBaseException().Message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment