public RestApiException(HttpResponseStatusCode statusCode, string reasonPhrase, RestApiErrorJsonModel errorModel) : base(GetErrorMessage(statusCode, reasonPhrase, errorModel)) { StatusCode = statusCode; ReasonPhrase = reasonPhrase; ErrorModel = errorModel; }
private async ValueTask <Stream> InternalExecuteAsync(FormattedRoute route, IRestRequestContent content, IRestRequestOptions options) { content?.Validate(); var request = new DefaultRestRequest(route, content, options); var defaultOptions = options as DefaultRestRequestOptions; defaultOptions?.RequestAction?.Invoke(request); await RateLimiter.EnqueueRequestAsync(request).ConfigureAwait(false); var response = await request.WaitForCompletionAsync().ConfigureAwait(false); defaultOptions?.HeadersAction?.Invoke(new DefaultRestResponseHeaders(response.HttpResponse.Headers)); var responseStream = await response.HttpResponse.ReadAsync().ConfigureAwait(false); var statusCode = (int)response.HttpResponse.Code; if (statusCode > 199 && statusCode < 300) { return(responseStream); } if (statusCode > 499 && statusCode < 600) { throw new RestApiException(response.HttpResponse.Code, response.HttpResponse.ReasonPhrase, null); } RestApiErrorJsonModel errorModel = null; try { errorModel = Serializer.Deserialize <RestApiErrorJsonModel>(responseStream); } catch (Exception ex) { Logger.LogError(ex, "An exception occurred while attempting to deserialize the error model."); } finally { await responseStream.DisposeAsync().ConfigureAwait(false); } throw new RestApiException(response.HttpResponse.Code, response.HttpResponse.ReasonPhrase, errorModel); }
private static string GetMessage(HttpResponseStatusCode statusCode, RestApiErrorJsonModel errorModel) { // We create an easily readable exception message, example: // HTTP: 400 BadRequest. Error message: Invalid Form Body var message = $"HTTP: {(Enum.IsDefined(statusCode) ? $"{(int) statusCode} {statusCode}" : statusCode)}. Error message: {errorModel.Message}"; // We check if Discord provided more detailed error messages. if (errorModel.ExtensionData.TryGetValue("errors", out var errors) && errors is IJsonObject errorsObject) { // We extract the errors from the structure shown below. var extracted = ExtractErrors(errorsObject); // We append the errors the message created above, example: // embed.fields[0].name: "Must be 256 or fewer in length." // embed.fields[1].value: "This field is required" message += $"\n{string.Join('\n', extracted.Select(x => $"{x.Key}: {x.Value ?? "unknown error"}"))}"; }
public RestApiException(HttpResponseStatusCode statusCode, RestApiErrorJsonModel errorModel) : base($"HTTP {(Enum.IsDefined(statusCode) ? $"{(int) statusCode} {statusCode}" : statusCode)}. Error message: {errorModel.Message}") { StatusCode = statusCode; ErrorModel = errorModel; }
public RestApiException(HttpResponseStatusCode statusCode, RestApiErrorJsonModel errorModel) : base(GetMessage(statusCode, errorModel)) { StatusCode = statusCode; ErrorModel = errorModel; }