Skip to content

Instantly share code, notes, and snippets.

@milovidov983
Created September 5, 2019 16:07
Show Gist options
  • Save milovidov983/d3c966739141dc9de56c57945cf78194 to your computer and use it in GitHub Desktop.
Save milovidov983/d3c966739141dc9de56c57945cf78194 to your computer and use it in GitHub Desktop.
ExceptionFilter example
namespace SiteApi.Filters {
public class ExceptionFilter : IAsyncExceptionFilter {
private readonly IHostingEnvironment _hostingEnvironment;
public ExceptionFilter(IHostingEnvironment hostingEnvironment) {
_hostingEnvironment = hostingEnvironment;
}
public async Task OnExceptionAsync(ExceptionContext context) {
context.ExceptionHandled = false;
var requestInfos = await GetRequestInfos(context.HttpContext?.Request);
_ = RollbarLocator.RollbarInstance.Error(context.Exception, requestInfos);
if (_hostingEnvironment.IsProduction()) {
context.Result = new NotFoundResult();
}
}
private async Task<Dictionary<string, object>> GetRequestInfos(HttpRequest request) {
if (request == null) {
return new Dictionary<string, object> { { "additionalInfo", "Отсутствует контекст вызова HttpRequest" } };
}
var requestData = new Dictionary<string, object> {
{ "path", request.Path },
{ "query", request.Query },
{ "queryString", request.QueryString },
{ "method", request.Method },
{ "contentType", request.ContentType } };
if (request.Headers != null) {
foreach (var item in request.Headers) {
requestData.TryAdd(item.Key, item.Value);
}
}
if (request.Method?.ToLowerInvariant() == "post" && request.Body != null) {
string body = "No json data.";
if (request.ContentType == "application/json") {
try {
using (var sr = new StreamReader(request.Body)) {
if (sr.BaseStream.CanRead && sr.BaseStream.CanSeek) {
request.Body.Seek(0, SeekOrigin.Begin);
body = await sr.ReadToEndAsync();
}
}
} catch { /*что бы не упасть там где падать совсем не следует */}
}
if (!requestData.TryAdd("requestBody", body)) {
requestData["requestBody"] = body;
}
}
return requestData;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment