public void ExecuteInBackground(Func <Task> action) { action.Invoke().ContinueWith(async task => { if (task.IsFaulted) { await logger.LogAsync(task.Exception); } }); }
public override async Task OnExceptionAsync(ExceptionContext context) { if (env.IsProduction() || env.IsStaging()) { await logger.LogAsync(context.Exception); context.Result = new StatusCodeResult(500); } else { throw context.Exception; } }
private async Task HandleExceptionAsync(HttpContext context, Exception exc) { if (exc is AggregateException) { exc = exc.InnerException; } logger.LogError(exc.ToString()); string errorMsg = logOptions.ShowErrorDetailsInResponse ? exc.ToString() : Constant.DefaultErrorMsg; StringValues stringValues = context.Request.Headers[Constant.Protocol]; Guid protocol; if (stringValues != StringValues.Empty && stringValues.Any()) { Guid.TryParse(stringValues.FirstOrDefault(), out protocol); } else { protocol = Guid.NewGuid(); context.Request.Headers.Add(Constant.Protocol, protocol.ToString()); } if (logOptions.EnableLogError) { IErrorLogger customErrorLogger = context.RequestServices.GetService <IErrorLogger>(); try { if (customErrorLogger == null) { if (!string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { if (!Directory.Exists(logOptions.DirectoryToLogErrorsOnFail)) { Directory.CreateDirectory(logOptions.DirectoryToLogErrorsOnFail); } File.AppendAllText(Path.Combine(logOptions.DirectoryToLogErrorsOnFail, $"LogError-{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.txt"), exc.ToString()); } } else { string loggedUser = context?.User?.Identity?.Name; string ipCliente = accessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(); string requestUrl = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(context.Request); if (logOptions.LogErrorInBackground) { customErrorLogger.LogAsync(exc, protocol, loggedUser, ipCliente, requestUrl, context.Request.Method, context); } else { Result resultLog = await customErrorLogger.LogAsync(exc, protocol, loggedUser, ipCliente, requestUrl, context.Request.Method, context); if (!resultLog.Valid && !string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { LogFailInFile(exc, JsonConvert.SerializeObject(resultLog, Formatting.Indented)); } } } } catch (Exception logExc) { if (!string.IsNullOrWhiteSpace(logOptions.DirectoryToLogErrorsOnFail)) { LogFailInFile(exc, logExc.ToString()); } if (!logOptions.IgnoreExceptionsOccuredInLogProcess) { throw; } } } if (string.IsNullOrWhiteSpace(logOptions.RedirectToPageIfIsNotAjaxRequest)) { var result = new Result { Protocol = protocol }; result.Set(ResultCode.GenericError, errorMsg); string resultJson = JsonConvert.SerializeObject(result); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)result.ResultCode; await context.Response.WriteAsync(resultJson); } else { if (context.Request.IsAjaxRequest()) { var result = new Result { Protocol = protocol }; result.Set(ResultCode.GenericError, errorMsg); string resultJson = JsonConvert.SerializeObject(result); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)result.ResultCode; await context.Response.WriteAsync(resultJson); } else { context.Response.Redirect(logOptions.RedirectToPageIfIsNotAjaxRequest, true); } } }
private async Task TranslateFromGlobalizationApiAsync(HttpContext context, MemoryStream responseBody, string headerAcceptLanguage, Result resultResponse, string responseBodyStr, bool successResult, string successCacheKey) { Result <string> resultToken = await tokenManager.GetAccessTokenAsync(); if (!resultToken.Valid) { string errorMsg = $"{nameof(TranslationMiddleware)}: Error on get token. Details: {resultToken.Message}"; logger.LogCritical(errorMsg); await errorLogger.LogAsync(new Exception(errorMsg), Guid.NewGuid(), null, null, nameof(TranslationMiddleware), null); return; } string token = resultToken.Value; try { HttpClient httpClient = httpClientFactory.CreateClient(); httpClient.BaseAddress = new Uri(translateOptions.BaseUrl); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); httpClient.DefaultRequestHeaders.Add("Accept-Language", headerAcceptLanguage); httpClient.DefaultRequestHeaders.Add("TranslateRequest", "true"); httpClient.Timeout = translateOptions.ApiTimeout ?? new TimeSpan(0, 0, 5); string requestTranslate = JsonConvert.SerializeObject(new Result().SetFromAnother(resultResponse)); HttpResponseMessage response = await httpClient.PostAsync(translateOptions.ResultTranslateRoute, new StringContent(requestTranslate, Encoding.UTF8, "application/json")); if (response != null && response.IsSuccessStatusCode) { string resultTranslateStr = await response.Content.ReadAsStringAsync(); Result resultTranslate = JsonConvert.DeserializeObject <Result>(resultTranslateStr); var jObject = JObject.Parse(responseBodyStr); UpdateJsonWithTranslateValues(resultTranslate, jObject); string newResponseBodyStr = jObject.ToString(); if (successResult) { using (ICacheEntry entryCache = memoryCache.CreateEntry(successCacheKey)) { entryCache.Value = resultTranslate?.Message ?? resultResponse?.Message; entryCache.AbsoluteExpirationRelativeToNow = translateOptions.CacheTimeoutForSuccessResultTranslation; } } RewriteReponse(context, responseBody, newResponseBodyStr); } } catch (Exception exc) { await TryLogErrorAsync(exc); if (translateOptions.ThrowExceptionWhenErrorOcurrInTranslate) { throw new Exception("Error in translation middleware.", exc); } } }