public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!context.ModelState.IsValid) { var errors = context.ModelState.Select( modelState => new UserErrorMessage( HttpStatusCode.BadRequest, modelState.Value.Errors.Select(e => e.ErrorMessage).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{s2}"), new Dictionary <string, object>() { { modelState.Key, modelState.Value?.RawValue?.ToString() ?? "" } }) ).ToArray(); var errorResponseMessage = new ErrorResponseMessage(errors); context.Result = new ContentResult { StatusCode = (int)HttpStatusCode.BadRequest, Content = JsonConvert.SerializeObject(errorResponseMessage), ContentType = "application/json", }; return; } else { await next(); } }
private static string Describe(ErrorResponseMessage errorMessage) { if (errorMessage.ErrorCount == 0) { return("Server returned an error with no description."); } var sb = StringBuilderPool.Get(); try { for (var i = 0; i < errorMessage.ErrorCount - 1; ++i, sb.Append(", ")) { var error = errorMessage.Errors[i]; sb.Append(error.Value); } return(sb.ToString()); } finally { StringBuilderPool.Free(ref sb); } }
public void Inquiry_WhenCalled__WithInvalidEmail_MustReturnsErrorResponseMessage_InvalidEmail() { //Arrange var mockCustomerService = new Mock <ICustomerService>(); var validId = 1; var validEmail = "*****@*****.**"; var customer = new Customer { CustomerId = validId, Name = "Customer 1", Email = validEmail, MobileNo = "0891234567" }; mockCustomerService.Setup(s => s.GetCustomerByIdAndEmail(validId, validEmail)).Returns(customer); CustomersController controller = new CustomersController(mockCustomerService.Object); var invalidEmail = "invalid@email"; var criteria = new CustomerInquiryRequestMessage { Email = invalidEmail }; //Act var action = controller.Inquiry(criteria); var badRequestResult = action.Result as BadRequestObjectResult; var actual = badRequestResult?.Value as ErrorResponseMessage; var expected = new ErrorResponseMessage { Message = "Invalid Email" }; //Assert Assert.Equal(expected.Message, actual?.Message); }
/// <summary> /// Конвертирует <see cref="IResponseMessage"/> в <see cref="ActionResult"/> с помощью указанной лямбда-функции, либо возвращает BadRequest. /// </summary> /// <typeparam name="TResposeType">Тип ответа, передаваемый в лямбда функцию.</typeparam> /// <typeparam name="TResult">Желаемый тип для <see cref="ActionResult"/>.</typeparam> /// <param name="response">Пришедший ответ.</param> /// <param name="continueWith">Лямбла-функция.</param> /// <returns>Ответ веб сервера.</returns> public static ActionResult <TResult> ToActionResult <TResposeType, TResult>(this IResponseMessage response, Func <TResposeType, ActionResult <TResult> > continueWith) { return(response switch { ErrorResponseMessage e => new ObjectResult(e.Message) { StatusCode = (int)HttpStatusCode.BadRequest }, _ => continueWith((TResposeType)response) });
private HttpResponseMessage CreateErrorResponse(string code, string msg) { var temp = new StdMsg <IResponseMessage>(_bodyConverter) { ContentType = ContentType.JSON, }; var t = new ErrorResponseMessage(); t.error_code = code; t.error_message = msg; temp.Data = t; return(temp.CreateResponseMsg(System.Net.HttpStatusCode.InternalServerError)); }
protected virtual async Task <bool> EnsureSuccessStatusCode(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { ErrorResponseMessage error = null; if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == "application/json") { // Attempt to read the error data from the service. var errorText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { error = JsonConvert.DeserializeObject <ErrorResponseMessage>(errorText); } catch (Exception) { // Error deserialization failed, attempt to get some data for the client error = new ErrorResponseMessage() { Error = new Error() { Code = "Unknown", Message = errorText, }, }; } } else { // Unrecognized content type error = new ErrorResponseMessage() { Error = new Error() { Code = response.StatusCode.ToString(), Message = string.Format("HTTP {0} Error: {1}", response.StatusCode.ToString(), response.ReasonPhrase), }, }; } throw new KeyVaultClientException(response.StatusCode, response.RequestMessage.RequestUri, error != null ? error.Error : null); } return(true); }
public void Inquiry_WhenCalled__WithNullRequestParameter_MustReturnsErrorResponseMessage_NoInquiryCriteria() { //Arrange var mockCustomerService = new Mock <ICustomerService>(); CustomersController controller = new CustomersController(mockCustomerService.Object); //Act var action = controller.Inquiry(null); var badRequestResult = action.Result as BadRequestObjectResult; var actual = badRequestResult?.Value as ErrorResponseMessage; var expected = new ErrorResponseMessage { Message = "No inquiry criteria" }; //Assert Assert.Equal(expected.Message, actual?.Message); }
public async Task Get_simple_formatted_error_message() { // Arrange var ex = new Exception(); // Act using (var apiClient = new Customer()) { ex = Assert.ThrowsAsync <Exception>(async() => await apiClient.GetAsync(Guid.NewGuid().ToString()).ConfigureAwait(false)); }; // Act var errors = await ErrorResponseMessage.BuildAsync(ex.Message).ConfigureAwait(false); // Assert Assert.That(errors.Errors, Is.Not.Empty); Assert.That(errors.Errors.First().Errors.First(), Is.EqualTo("Customer Not Found")); Assert.That(errors.StatusCode, Is.EqualTo(404)); Assert.That(errors.ReasonPhase, Is.EqualTo("Not Found")); }
public static void UseMyCustomExceptionMiddleware(this IApplicationBuilder app) { app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); var errorResponse = new ErrorResponseMessage() { Message = contextFeature.Error.Message, FriendlyMessage = "## Error From Middleware MyCustomExceptionMiddleware ##", StackTrace = contextFeature.Error.StackTrace }; await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse)); }); }); }
public async Task Get_complex_formatted_error_message() { // Arrange var myClient = new CustomerModel(); var request = new Fixture().Build <CustomerRequestMessage>() .With(a => a.Email, "invalid email") .With(a => a.CpfOrCnpj, "1111111111") .Create(); var ex = new Exception(); using (var apiClient = new Customer()) { ex = Assert.ThrowsAsync <Exception>(async() => await apiClient.CreateAsync(request, null).ConfigureAwait(false)); }; // Act var errors = await ErrorResponseMessage.BuildAsync(ex.Message).ConfigureAwait(false); // Assert Assert.That(errors.Errors, Is.Not.Empty); Assert.That(errors.StatusCode, Is.EqualTo(422)); Assert.That(errors.ReasonPhase, Is.EqualTo("Unprocessable Entity")); }
/// <summary> /// Validate the response status. /// </summary> /// <param name="response">HttpResponseMessage</param> /// <returns>HttpResponseMessage</returns> internal static async Task <HttpResponseMessage> EnsureSuccessStatusCodeAsync(this HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return(response); } else { ErrorResponseMessage errorMessage; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { var jsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }; jsonSerializerSettings.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); errorMessage = JsonConvert.DeserializeObject <ErrorResponseMessage>(content, jsonSerializerSettings); } catch { errorMessage = new ErrorResponseMessage() { Message = content, Details = new ErrorDetail[0] }; } throw new LineResponseException(errorMessage.Message) { StatusCode = response.StatusCode, ResponseMessage = errorMessage }; } }
/// <summary> /// Gets the error message for the exception based on the <paramref name="response"/> and <paramref name="errorResponse"/> parameters. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> that was sent.</param> /// <param name="response">The <see cref="HttpResponseMessage"/> to read.</param> /// <param name="errorResponse">The <see cref="ErrorResponseMessage"/>.</param> /// <returns></returns> private static async Task <string> GetErrorMessage(HttpRequestMessage request, HttpResponseMessage response, ErrorResponseMessage errorResponse) { var sb = new StringBuilder(); if (errorResponse != null) { sb.Append($"{errorResponse.Error.Code} : {errorResponse.Error.Message}"); } else { var rawResponse = await response.Content.ReadAsStringAsync(); sb.Append(rawResponse); } var headers = response?.Headers; if (response?.Headers == null) { return(sb.ToString()); } if (response.Headers.TryGetValues("x-ms-correlation-request-id", out var correlationIds)) { sb.AppendLine().AppendFormat("CorrelationId: {0}", correlationIds.First()); } return(sb.ToString()); }
/// <summary> /// Gets the error message for the exception based on the <paramref name="response"/> and <paramref name="errorResponse"/> parameters. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> that was sent.</param> /// <param name="response">The <see cref="HttpResponseMessage"/> to read.</param> /// <param name="errorResponse">The <see cref="ErrorResponseMessage"/>.</param> /// <returns></returns> private static Task <string> GetErrorMessage(HttpRequestMessage request, HttpResponseMessage response, ErrorResponseMessage errorResponse) { return(errorResponse != null ? Task.FromResult(string.Format("{0} : {1}", errorResponse.Error.Code, errorResponse.Error.Message)) : response.Content.ReadAsStringAsync()); }
internal PostgresErrorException(ErrorResponseMessage errorMessage) : base(Describe(errorMessage)) { }
/// <summary> /// Gets the error message for the exception based on the <paramref name="response"/> and <paramref name="errorResponse"/> parameters. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> that was sent.</param> /// <param name="response">The <see cref="HttpResponseMessage"/> to read.</param> /// <param name="errorResponse">The <see cref="ErrorResponseMessage"/>.</param> /// <returns></returns> private static Task <string> GetErrorMessage(HttpRequestMessage request, HttpResponseMessage response, ErrorResponseMessage errorResponse) { return(errorResponse != null ? Task.FromResult(errorResponse.ToFormattedJson()) : response.Content.ReadAsStringAsync()); }
private void WriteErrorMessage(HttpContext context, IContentSerializer serializer, ErrorResponseMessage errorResponseMessage) { context.Response.ContentType = serializer.ContentType; serializer.SerializeResponse(context.Response.Body, errorResponseMessage, context); }