public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next.Invoke(context); } catch (Exception ex) { _logger.LogError(ex, ex.Message); _sentry?.CaptureException(ex); var exception = ex as CrpcException; if (!(ex is CrpcException)) { // TODO(0xdeafcafe): How should this be done? exception = new CrpcException(CrpcCodes.Unknown); } var json = JsonConvert.SerializeObject(exception, _jsonSerializerSettings); context.Response.StatusCode = exception.StatusCode(); context.Response.ContentType = "application/json; charset=utf-8"; await context.Response.WriteAsync(json); } }
public async Task TestGenericCrpcException() { var middleware = new ExceptionMiddleware(_loggerFactory, null); var context = new DefaultHttpContext(); var thrownException = new CrpcException(CrpcCodes.ValidationFailed); context.Response.Body = new MemoryStream(); await middleware.InvokeAsync(context, (ctx) => throw thrownException); context.Response.Body.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(context.Response.Body); var body = reader.ReadToEnd(); var exception = JsonConvert.DeserializeObject <CrpcException>(body); Assert.Equal(CrpcCodes.ValidationFailed, exception.Message); Assert.Equal(thrownException.StatusCode(), (int)context.Response.StatusCode); }