public static string SanitizedExceptionMessage(this FlurlHttpException exception) { const string expression = @"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}(\:[0-9]+)?\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)"; return(Regex.Replace(exception.ToString(), expression, match => SanitizeUrl(match.Value).ToString())); }
/* error and success callbacks */ private void HandleRegisterError(FlurlHttpException ex) { switch (ex.Call.HttpStatus) { case HttpStatusCode.BadRequest: var response = ex.GetResponseJson(); AlertContent.Text = string.Empty; if (response.message == TwatsAppService.API.ModelStateErrorMessage) { foreach (var error in response.modelState) { foreach (string msg in error.Value) { AlertContent.Text += $"{msg}\n"; } } } else { AlertContent.Text = response.message; } break; case HttpStatusCode.InternalServerError: AlertContent.Text = TwatsAppService.API.GenericInternalServerErrorMessage; break; default: AlertContent.Text = TwatsAppService.API.CrazyShitErrorMessage; break; } AlertLabel.Visibility = Visibility.Visible; }
private static async Task HandleFlurlHttpException <TResult>(FlurlHttpException httpException, Func <Task <TResult> > func, Func <TResult, Task> successCallback, Func <System.Exception, Task> failCallback) { if (await new ExceptionHandler(dialogService).HandleIfAbpResponseAsync(httpException)) { await failCallback(httpException); return; } var httpExceptionMessage = LocalTranslationHelper.Localize("HttpException"); #if DEBUG httpExceptionMessage += Environment.NewLine + httpException.Message; #endif var accepted = dialogService.Question( LocalTranslationHelper.Localize("MessageTitle"), httpExceptionMessage); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpException); } }
private static async Task HandleFlurlHttpException <TResult>(FlurlHttpException httpException, Func <Task <TResult> > func, Func <TResult, Task> successCallback, Func <System.Exception, Task> failCallback) { if (await new AbpExceptionHandler().HandleIfAbpResponseAsync(httpException)) { await failCallback(httpException); return; } var httpExceptionMessage = LocalTranslation.HttpException; if (Debugger.IsAttached) { httpExceptionMessage += Environment.NewLine + httpException.Message; } var accepted = await UserDialogs.Instance.ConfirmAsync(httpExceptionMessage, LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); if (accepted) { await Execute(func, successCallback, failCallback); } else { await failCallback(httpException); } }
/// <summary> /// TODO: Document me. /// </summary> /// <param name="flurlException"></param> /// <returns></returns> public static bool IsDnsResolveError(this FlurlHttpException flurlException) { if (flurlException == null) { throw new ArgumentNullException(nameof(flurlException)); } // net 4.6 if ((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException.InnerException.Message != null) && flurlException.InnerException.InnerException.Message.Contains( "remote name could not be resolved")) { return(true); } // core if ((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException?.InnerException?.Message?.Contains( "server name or address could not be resolved") ?? false)) { return(true); } // Linux return((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException?.InnerException?.Message != null) && flurlException.InnerException.InnerException.Message.Contains("resolve host name")); }
public static HttpResponseMessage FlurlExceptionResponse(FlurlHttpException ex, HttpRequestMessage request = null) { var details = "An error has occured on an external request."; if (request != null) { // Will show detailed error message useful for developers / debuggers. if (request.Headers.Contains("X-Debug")) { details = ex.Call.Response.Content.ReadAsStringAsync().Result; } } return(new HttpResponseMessage { StatusCode = ex.Call.Response.StatusCode, Content = CreateStringContent( new { details = string.Format(FlurlExceptionResponseTemplate, details), exceptionType = ex.GetType().Name, callDetails = ex.Message }) }); }
public static async Task <ApiException> CreateApiExceptionAsync(this FlurlHttpException source) { var rawResponse = await source.GetResponseStringAsync(); try { var apiErrorResponse = await source .GetResponseJsonAsync <ApiErrorResponse>() .ConfigureAwait(false); apiErrorResponse.Error.RawResponse = rawResponse; return(CreateApiExceptionFrom(source, apiErrorResponse)); } catch (JsonException ex) { var message = "An unexpected problem occurred while parsing the expected JSON response. See the RawResponse property, and the inner exception, for details."; return(new ApiException( message, source, new ApiError { Code = 500, Message = ex.Message, RawResponse = rawResponse, Type = "gocardless" })); } }
public static bool HandleIfAbpResponse(FlurlHttpException httpException) { var errorResponse = httpException.Call.ErrorResponseBody; if (errorResponse == null) { return(false); } if (!errorResponse.Contains("__abp")) { return(false); } var ajaxResponse = JsonConvert.DeserializeObject <AjaxResponse>(errorResponse); if (ajaxResponse?.Error == null) { return(false); } UserDialogs.Instance.HideLoading(); if (string.IsNullOrEmpty(ajaxResponse.Error.Details)) { UserDialogs.Instance.Alert(ajaxResponse.Error.GetConsolidatedMessage(), L.Localize("Error")); } else { UserDialogs.Instance.Alert(ajaxResponse.Error.Details, ajaxResponse.Error.GetConsolidatedMessage()); } return(true); }
private Exception CreateException(FlurlHttpException captureException) { if (captureException is FlurlHttpTimeoutException || captureException.Call.HttpStatus.HasValue == false) { ExceptionDispatchInfo.Capture(captureException.InnerException).Throw(); } var exceptionMessage = captureException.Call.Response.ReasonPhrase; var errorResponseText = captureException.GetResponseString(); if (string.IsNullOrWhiteSpace(errorResponseText) == false) { try { var deserializerMessage = captureException.GetResponseJson <ApiErrorResponse>()?.ToString(); exceptionMessage = string.IsNullOrWhiteSpace(deserializerMessage) ? errorResponseText : deserializerMessage; } catch { exceptionMessage = errorResponseText; } } if (_exceptionsTypesByStatusCodes.TryGetValue(captureException.Call.Response.StatusCode, out var exceptionType)) { return((Exception)Activator.CreateInstance(exceptionType, exceptionMessage)); } return(new ApiException(captureException.Call.Response.StatusCode, exceptionMessage)); }
/// <summary> /// TODO: Document me. /// </summary> /// <param name="flurlException"></param> /// <returns></returns> public static bool IsCertificateError(this FlurlHttpException flurlException) { // core if ((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException?.InnerException?.Message == "A security error occurred")) { return(true); } // net 4.6 if ((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException?.InnerException?.Message?.Contains("A security error occurred") ?? false) && (flurlException.InnerException?.InnerException?.InnerException?.Message?.Contains("handshake failed") ?? false)) { return(true); } // Linux if ((flurlException.Call.Response == null) && (flurlException.InnerException?.GetType() == typeof(HttpRequestException)) && (flurlException.InnerException?.InnerException?.Message?.Contains("SSL") ?? false)) { return(true); } return(false); }
public static async Task <bool> HandleIfAbpResponseAsync(FlurlHttpException httpException) { var errorResponse = await httpException.GetResponseStringAsync(); if (errorResponse == null) { return(false); } if (!errorResponse.Contains("__abp")) { return(false); } var ajaxResponse = JsonConvert.DeserializeObject <AjaxResponse>(errorResponse); if (ajaxResponse?.Error == null) { return(false); } UserDialogs.Instance.HideLoading(); if (string.IsNullOrEmpty(ajaxResponse.Error.Details)) { UserDialogs.Instance.Alert(ajaxResponse.Error.GetConsolidatedMessage(), "Error".Translate()); } else { UserDialogs.Instance.Alert(ajaxResponse.Error.Details, ajaxResponse.Error.GetConsolidatedMessage()); } return(true); }
public async Task <bool> HandleIfAbpResponseAsync(FlurlHttpException httpException) { var ajaxResponse = await httpException.GetResponseJsonAsync <AjaxResponse>(); if (ajaxResponse == null) { return(false); } if (!ajaxResponse.__abp) { return(false); } if (ajaxResponse.Error == null) { return(false); } UserDialogs.Instance.HideLoading(); if (string.IsNullOrEmpty(ajaxResponse.Error.Details)) { UserDialogs.Instance.Alert(ajaxResponse.Error.GetConsolidatedMessage(), L.Localize("Error")); } else { UserDialogs.Instance.Alert(ajaxResponse.Error.Details, ajaxResponse.Error.GetConsolidatedMessage()); } return(true); }
/// <summary> /// The HandleFlurlHttpException /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="httpException">The httpException<see cref="FlurlHttpException"/></param> /// <param name="func">The func<see cref="Func{Task{TResult}}"/></param> /// <param name="successCallback">The successCallback<see cref="Func{TResult, Task}"/></param> /// <param name="failCallback">The failCallback<see cref="Exception"/></param> /// <returns>The <see cref="Task"/></returns> private static async Task HandleFlurlHttpException <TResult>(FlurlHttpException httpException, Func <Task <TResult> > func, Func <TResult, Task> successCallback, Func <System.Exception, Task> failCallback) { if (await AbpExceptionHandler.HandleIfAbpResponseAsync(httpException)) { await failCallback(httpException); return; } //UserDialogs.Instance.Toast(Resources.HttpException, TimeSpan.FromSeconds(10)); //var accepted = await UserDialogs.Instance.ConfirmAsync(LocalTranslation.HttpException, // LocalTranslation.MessageTitle, LocalTranslation.Ok, LocalTranslation.Cancel); //if (accepted) //{ // await Execute(func, successCallback, failCallback); //} //else //{ // await failCallback(httpException); //} }
public String ConvertToString(FlurlHttpException Except) { String Result = ""; String ErrantJsonContent = ""; Result = Except.GetResponseStringAsync().GetAwaiter().GetResult(); HttpContent res2 = Except.Call.Response.Content; ErrantJsonContent = res2.ReadAsStringAsync().Result; if (Result != ErrantJsonContent) { Result += " ContentErrantJson: " + ErrantJsonContent; } Result = Result.Replace(":[{", ""); Result = Result.Replace("{", ""); Result = Result.Replace("}]}", ""); Result = Result.Replace("}", ""); Result = Result.Replace('"', ' '); Result = Result.Replace(":", ""); Result = Result.Replace(",", ""); Result = Result.Replace("errors", "ParĂ¢metros Invalidos: "); Result = Result.Replace("invalid_parameter", ""); Result = Result.Replace("parameter", ""); Result = Result.Replace("message", ""); Result = Result.Replace(" ", " "); Result = Result.Replace(" ", " "); Result = Result.Replace("id ", "\n"); Result = Result.Trim(); return(Result); }
public async Task <bool> HandleIfAbpResponseAsync(FlurlHttpException httpException) { AjaxResponse ajaxResponse = await httpException.GetResponseJsonAsync <AjaxResponse>(); if (ajaxResponse == null) { return(false); } if (!ajaxResponse.__abp) { return(false); } if (ajaxResponse.Error == null) { return(false); } if (IsUnauthroizedResponseForSessionTimoutCase(httpException, ajaxResponse)) { return(true); } if (string.IsNullOrEmpty(ajaxResponse.Error.Details)) { dialog.ShowMessage(Local.Localize("Error"), ajaxResponse.Error.GetConsolidatedMessage()); } else { dialog.ShowMessage(ajaxResponse.Error.GetConsolidatedMessage(), ajaxResponse.Error.Details); } return(true); }
internal CosmosHttpException(FlurlHttpException innerException) : base(innerException.Message, innerException) { Request = innerException.Call.Request; Response = innerException.Call.Response; EndedUtc = innerException.Call.EndedUtc; StartedUtc = innerException.Call.StartedUtc; Url = innerException.Call.FlurlRequest.Url; }
private static void FlurlHttpExceptionHandler(FlurlHttpException exception) { var call = exception.Call; var status = call.Response?.StatusCode; var error = call.Exception?.Message ?? "Something happened to the HTTP call."; throw new EcwidHttpException(error, status, exception); }
private static bool IsTimeoutException(this FlurlHttpException This) { if (This is FlurlHttpTimeoutException) { return(true); } return(This.InnerException is OperationCanceledException); }
private static bool IsInvalidHostException(this FlurlHttpException This) { var be = This.GetBaseException(); return(This.Call != null && !This.Call.Completed && This.Call.Response == null && be is SocketException); }
private static EtcdErrorCode?GetEtcdErrorCode(this FlurlHttpException This) { if (This == null || This.Call == null || This.Call.Response == null) { return(null); } return(This.Call.Response.StatusCode.Map()); }
private async Task <ApiException> HandleException <TResponseError>(FlurlHttpException exception) { ApiException returnException; if (exception.Call.Response != null) { string response = null; try { response = await exception.Call.Response.Content.ReadAsStringAsync(); } catch { // ignored } if (String.IsNullOrWhiteSpace(response)) { returnException = new ApiException(exception.Call.Response.StatusCode); } else if (response.IsValidJson()) { var exceptionType = typeof(TResponseError); if (exceptionType.FullName == "System.Object") { dynamic jsonObject = ApiConfiguration.SerializerSettings != null ? JsonConvert.DeserializeObject <dynamic>(response, ApiConfiguration.SerializerSettings) : JsonConvert.DeserializeObject <dynamic>(response); returnException = new ApiException(exception.Call.Response.StatusCode, jsonObject); } else { var jsonObject = ApiConfiguration.SerializerSettings != null ? JsonConvert.DeserializeObject <TResponseError>(response, ApiConfiguration.SerializerSettings) : JsonConvert.DeserializeObject <TResponseError>(response); returnException = new ApiException <TResponseError>(exception.Call.Response.StatusCode, jsonObject); } } else { returnException = new ApiException($"Failed with response '{response}'", exception.Call.Response.StatusCode); } } else if (exception.Call.Exception.Message.ToLower().Contains("fail")) { returnException = new ApiException(exception.Message, HttpStatusCode.GatewayTimeout); } else { returnException = new ApiException(exception.Message); } return(await Task.FromResult(returnException)); }
protected Exception TokenExpiredOrOriginalException(FlurlHttpException e) { // Assume token expired if (e.Call.HttpStatus == HttpStatusCode.Unauthorized) { return(new TokenExpiredException()); } return(e); }
private static EtcdException AsHttpConnectionException(this FlurlHttpException This) { var webex = This.GetBaseException() as WebException; if (webex == null || string.IsNullOrWhiteSpace(webex.Message)) { return(new HttpConnectionException()); } return(new HttpConnectionException(webex.Message)); }
private static bool ShouldTryAgain(FlurlHttpException flurlHttpException) { switch ((int)flurlHttpException.Call.Response.StatusCode) { case 500: return(true); default: return(false); } }
/// <summary> /// Check if a request to provision a Public IP failed because of a race condition /// between when we created the server and when we requested the IP /// i.e. The RackConnect API asked for the server details from the server API and got back a 404 /// </summary> private static bool AssignIPFailedDueToServerCreationRaceCondition(FlurlHttpException ex) { if (ex.Call.HttpStatus != HttpStatusCode.Conflict) { return(false); } string errorMessage = ex.GetResponseString(); return(Regex.IsMatch(errorMessage, "Cloud Server .* (unprocessable|exist).*")); }
public ProcessResultException(FlurlHttpException ex) { this.Message = ex.Message; try { this.ResponseBody = ex.GetResponseJsonAsync().Result; } catch (Exception) { this.ResponseBody = "Error while trying to parse response body"; } }
private static async Task <Result <T> > HandleException <T>(FlurlHttpException ex) { var result = await ex.GetResponseJsonAsync <Result>(); if (result != null && result.Success == false) { return(Result.Failure <T>(result.Errors)); } return(await HandleException <T>(ex as Exception)); }
public static System.Exception ToQuandlException(this FlurlHttpException ex) { var str = ex.GetResponseString(); if (!string.IsNullOrWhiteSpace(str) && str.Contains("quandl_error")) { dynamic content = JsonConvert.DeserializeObject(str); return(new QuandlException(content.quandl_error.code.ToString(), content.quandl_error.message.ToString())); } return(ex); }
private static bool IsTransientError(FlurlHttpException exception) { int[] httpStatusCodesWorthRetrying = { (int)HttpStatusCode.RequestTimeout, // 408 (int)HttpStatusCode.BadGateway, // 502 (int)HttpStatusCode.ServiceUnavailable, // 503 (int)HttpStatusCode.GatewayTimeout // 504 }; return(exception.StatusCode.HasValue && httpStatusCodesWorthRetrying.Contains(exception.StatusCode.Value)); }
/// <summary> /// Parses the response body of the failed HTTP call return any error status messages. /// </summary> public static async Task <string> GetErrorMessageAsync(this FlurlHttpException ex) { if (ex is null) { return(null); } var error = await ex.GetResponseJsonAsync <JsonResponse>() .ConfigureAwait(false); return(error?.Message); }