Last active
December 22, 2015 19:29
-
-
Save danielmackay/6519627 to your computer and use it in GitHub Desktop.
Wrap function with Web API logging. #webapi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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