private async Task <HttpResponseMessage> BaseSendAsync( CateHttpContext context, HttpRequestMessage request, CancellationToken cancellationToken) { try { return(await base.SendAsync(request, cancellationToken) .ConfigureAwait(false)); } catch (Exception ex) { throw new CateHttpException(context, ex); } }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var context = CateHttpContext.Extract(request); context.Watch.Start(); try { await Emit(EventType.Start, context); context.Response = await BaseSendAsync(context, request, cancellationToken) .ConfigureAwait(false); context.Response.RequestMessage = request; if (context.Succeeded) { return(context.Response); } if (context.Response.Content != null) { context.ErrorBody = await context .Response.Content.ReadAsStringAsync().ConfigureAwait(false); } throw new CateHttpException(context); } catch (Exception ex) { context.Error = ex; await Emit(EventType.Error, context); throw; } finally { context.Watch.Stop(); await Emit(EventType.Ended, context); } }
public static async Task <T> Deserialize <T>(HttpResponseMessage response) { if (response == null) { return(default(T)); } if (!response.IsSuccessStatusCode) { return(default(T)); } var context = CateHttpContext.Extract(response.RequestMessage); try { if (response.IsJson()) { using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) return(context.Configuration.JsonSerializer.Deserialize <T>(stream)); } if (response.IsXml()) { using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) return(context.Configuration.XmlSerializer.Deserialize <T>(stream)); } throw new CateHttpException(context, $"Unsupported media type ({response.ContentMediaType()})", null); } catch (CateHttpException ex) { context.Error = ex; throw; } catch (Exception ex) { context.Error = ex; throw new CateSerializerException(context, typeof(T), ex); } }
internal static Task Emit(EventType on, CateHttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var configuration = context.Configuration; switch (on) { case EventType.Start: if (configuration.OnStartAsync == null) { return(TaskCompleted); } return(configuration.OnStartAsync(context)); case EventType.Error: if (configuration.OnErrorAsync == null) { return(TaskCompleted); } return(configuration.OnErrorAsync(context)); case EventType.Ended: if (configuration.OnEndedAsync == null) { return(TaskCompleted); } return(configuration.OnEndedAsync(context)); default: return(TaskCompleted); } }