public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (System.Exception ex) { // If it's NonSystemException, no need to send error email if (!(ex is NonSystemException)) { Logger.LogError(0, ex, "An unhandled exception has occurred: " + ex.Message); var errMessage = ErrorContentCreator.BuildContent(ex, context); Logger.LogError(errMessage); Options?.ManualProcess?.Invoke(ex); if (Options != null && Options.SendErrorEnabled) { try { await ErrorSender.SendAsync(errMessage); } catch (System.Exception ex2) { Logger.LogError(0, ex2, "An unhandled exception has occurred during send error email: " + ex2.Message); Logger.LogError(ErrorContentCreator.BuildContent(ex2)); } } } // Output error result if (Options != null && Options.OutputErrorResult) { var response = new ApiErrorResult(); var nonSystemException = ex as NonSystemException; if (nonSystemException != null) { response.Type = ErrorType.NonSystem; response.Code = nonSystemException.ErrorCode; response.Message = nonSystemException.Message; } else { response.Type = ErrorType.System; response.Message = Options.IsProduction ? Options.ProductionErrorMessage : ex.Message; } context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() })); } } }
internal Task HandleExceptionAsync(HttpContext context, Exception exception, bool applySensitiveInfoFilter = false) { // 500 if unexpected, would have been this anyway. var code = HttpStatusCode.InternalServerError; var message = exception.Message; // We will suppress exception messages under specific conditions, so replace message with default. if (applySensitiveInfoFilter) { message = $"An exception occurred of type {exception.GetBaseException().GetType().Name}. Message " + "has been suppressed, please contact support for more information."; } _logger?.LogError(exception, $"An unhandled exception has occurred while executing {context.Request.Method}"); // ApiErrorResponse will be output. var apiError = new ApiErrorResult(exception, message); var result = JsonConvert.SerializeObject(apiError); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; // Output result in response stream. return(context.Response.WriteAsync(result)); }
public async Task <IActionResult> Register([FromBody] RegisterViewModel newUser) { if (this.ModelState.IsValid) { IUserManager userManager = this.HttpContext.RequestServices.GetService(typeof(IUserManager)) as IUserManager; if (userManager == null) { throw new Exception("User Manager object not configured."); } SpaDatasource.Entitites.User user = new SpaDatasource.Entitites.User { Login = newUser.Login, Email = newUser.Email, FullName = newUser.FullName, Status = SpaDatasource.SystemRoles.Customer }; try { SpaDatasource.Entitites.User u = await userManager.FindByNameAsync(newUser.Login); if (u != null) { // alrady exists ApiErrorResult apiResultExistingUser = new ApiErrorResult { Messages = new List <string> () { "Пользователь с таким именем уже существует." } }; return(new JsonResult(apiResultExistingUser) { StatusCode = 409 }); } await userManager.CreateAsync(user, newUser.Password); return(Ok()); } catch (Exception ex) { this.ModelState.AddModelError(string.Empty, ex.Message); } } ApiErrorResult apiResultError = new ApiErrorResult { Messages = ModelState.Keys.SelectMany(key => this.ModelState[key].Errors).Select(x => x.ErrorMessage).ToList <string>() }; return(new JsonResult(apiResultError) { StatusCode = 500 }); }
private async Task RespondWithError( HttpContext context, string errorMessage, HttpStatusCode statusCode) { var apiResult = new ApiErrorResult(errorMessage); await RespondWithError(context, apiResult, statusCode); }
private IActionResult WriteError(HttpStatusCode statusCode, Exception e) { var result = new ApiErrorResult(e.Message, e) { StatusCode = (int)statusCode, }; return(result); }
private static async Task RespondWithError( HttpContext context, ApiErrorResult apiResult, HttpStatusCode statusCode) { context.Response.StatusCode = (int)statusCode; context.Response.ContentType = @"application/json"; string apiResultString = apiResult.ToJsonString(); await context.Response.WriteAsync(apiResultString); }
public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (System.Exception ex) { Logger.LogError(0, ex, "An unhandled exception has occurred: " + ex.Message); var errMessage = BuildErrorMessage(ex, context); Logger.LogError(errMessage); Options.ManualProcess?.Invoke(ex); if (Options?.MailOptions != null && MailSender != null) { try { await MailSender.SendEmailAsync(Options.MailOptions.To, Options.MailOptions.Subject, errMessage); } catch (System.Exception ex2) { Logger.LogError(0, ex2, "An unhandled exception has occurred during send error email: " + ex2.Message); Logger.LogError(BuildErrorMessage(ex2)); } } // Output error result if (Options != null && Options.OutputErrorResult) { var response = new ApiErrorResult(); if (ex is ExpectedException) { response.Type = ErrorType.Expected; response.Code = ((ExpectedException)ex).ErrorCode; response.Message = ex.Message; } else { response.Type = ErrorType.Unexpected; response.Message = ex.Message; } context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() })); } } }
public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { var apiErrorResult = new ApiErrorResult() { ValidationErrorMessages = actionContext.ModelState.GetAllErrorMessages() }; actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, apiErrorResult); } else { base.OnActionExecuting(actionContext); } }
public static IServiceCollection AddControllerServices(this IServiceCollection services) { services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }).AddControllersAsServices() .ConfigureApiBehaviorOptions(e => { e.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e1 => e1.Value.Errors.Count > 0) .Select(e1 => e1.Value.Errors.First().ErrorMessage); return(new JsonResult(ApiErrorResult.BadRequest(errors))); }; }); return(services); }
public void Test_ApiErrorResult_Instance(string key, string message) { // Arrange var serviceProviderMock = new Mock <IServiceProvider>(); serviceProviderMock.Setup(serviceProvider => serviceProvider.GetService(typeof(ILogger <ValidateModelAttribute>))) .Returns(Mock.Of <ILogger <ValidateModelAttribute> >()); var httpContext = new DefaultHttpContext { RequestServices = serviceProviderMock.Object }; // Act var err = new ApiErrorResult(new Exception(message), key); var servErr = new InternalServerErrorResult(new Exception(message)); var res = httpContext.Response; var req = httpContext.Request; var apiError = new ApiErrorMessage("", ""); apiError = new ApiErrorMessage(null, ""); apiError = new ApiErrorMessage("test", ""); // Assert err.Message.Should().Be(key); err.Errors.Count.Should().Be(1); err.Errors[0].Message.Should().Be(message); servErr.StatusCode.Should().Be(500); Assert.IsType <ApiErrorResult>(servErr.Value); res.Headers.Add(key, message); res.StatusCode = 200; res.Body = new MemoryStream(Encoding.ASCII.GetBytes(message)); res.ToFormattedString().Length.Should().BeGreaterThan(0); req.Headers.Add(key, message); req.Body = new MemoryStream(Encoding.ASCII.GetBytes(message)); req.ToFormattedString().Length.Should().BeGreaterThan(0); }
public async Task <ApiResult <bool> > Create(RegisterRequest request) { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration["BaseAddress"]); var jsonRequest = JsonConvert.SerializeObject(request); var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"/api/users", httpContent); var resultContent = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { var errorMessage = await response.Content.ReadAsStringAsync(); var result = new ApiErrorResult <bool>(JsonConvert.DeserializeObject <List <ErrorValidationVm> >(errorMessage)); return(result); } return(new ApiResult <bool>()); }
public void OnException(ExceptionContext context) { _logger.LogInformation(context.Exception, ThrowIf.GetInnerMostException(context.Exception).Message); Exception exception = ThrowIf.GetInnerMostException(context.Exception); IFilterMetadata rateLimitFilter = context.Filters.Where(x => x.GetType().Name == "RateLimitFilter").FirstOrDefault(); Type objectType = null; if (rateLimitFilter != null) { objectType = ((RateLimitFilter)rateLimitFilter).ObjectType; } ObjectResult objectResult = null; if (objectType == null) { ApiErrorResult apiError = new ApiErrorResult(); apiError.Message = exception != null ? exception.Message : "Unexpected Json Error"; apiError.StackTrace = exception?.StackTrace; objectResult = new ObjectResult(apiError); } else { IEntityService entityService = Activator.CreateInstance(((RateLimitFilter)rateLimitFilter).ObjectType) as IEntityService; entityService.Message = exception != null ? exception.Message : "Unexpected Json Error"; entityService.StackTrace = exception?.StackTrace; objectResult = new ObjectResult(entityService); } context.Result = new ObjectResult(objectResult) { StatusCode = context.HttpContext.Response.StatusCode }; }
public void OnException(ExceptionContext context) { if (context.Exception is ApiDomainException domainException) { //var aggregateMessage = domainException.Messages == null // ? context.Exception.Message // : JsonConvert.SerializeObject(domainException.Messages); //_logger.LogError(new EventId(context.Exception.HResult), // context.Exception, // aggregateMessage); var result = ApiErrorResult.BadRequest(domainException.Messages ?? new[] { context.Exception.Message }); context.Result = new BadRequestObjectResult(result); context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; } else { _logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); object devMessage = null; if (_env.IsDevelopment()) { devMessage = LogFormatter.PrintException(context.Exception); } var result = ApiExceptionResult.InternalServerError(new[] { "An server error occur." }, devMessage); context.Result = new InternalServerErrorObjectResult(result); context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; } context.ExceptionHandled = true; }
public JsonResult Shorten() { try { var url = Request["url"]; var hash = service.Shorten(url.Trim()); var result = new ApiShortenResult { Success = true, Message = "success", Hash = hash, LongUrl = url }; return(Json(result, JsonRequestBehavior.AllowGet)); } catch (ShortnerValidationException ex) { var validationResult = new ApiErrorResult { Success = false, Errors = ex.Errors, Message = ex.Message }; Response.StatusCode = 500; Response.TrySkipIisCustomErrors = true; return(Json(validationResult)); } catch (Exception ex) { var exResult = new ApiResult { Success = false, Message = ex.Message }; Response.StatusCode = 500; Response.TrySkipIisCustomErrors = true; return(Json(exResult)); } }
public void OnException(ExceptionContext context) { var exception = context.Exception; logger.LogError( new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); if (context.Exception.GetType() == typeof(BusinessException) || context.Exception.GetType().BaseType == typeof(BusinessException)) { // handle bussiness exception var json = new ApiErrorResult { Success = false, ErrorCode = context.Exception.GetType().Name, ErrorMessage = context.Exception.Message, }; // Result asigned to a result object but in destiny the response is empty. This is a known bug of .net core 1.1 //It will be fixed in .net core 1.1.2. See https://github.com/aspnet/Mvc/issues/5594 for more information context.Result = new BadRequestObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } else { // if it's not one of the expected exception, set it to 500 var code = HttpStatusCode.InternalServerError; //TODO:Mapping if (exception is NotFoundExe) code = HttpStatusCode.NotFound; switch (exception) { case EntityNotFoundException _: code = HttpStatusCode.NotFound; break; case ArgumentNullException _: code = HttpStatusCode.BadRequest; break; case InvalidArgumentException _: code = HttpStatusCode.BadRequest; break; case HttpRequestException _: code = HttpStatusCode.BadRequest; break; case UnauthorizedAccessException _: code = HttpStatusCode.Unauthorized; break; } // Result asigned to a result object but in destiny the response is empty. This is a known bug of .net core 1.1 // It will be fixed in .net core 1.1.2. See https://github.com/aspnet/Mvc/issues/5594 for more information context.Result = new ObjectResult( new ApiErrorResult { Success = false, ErrorCode = code.ToString(), ErrorMessage = exception.InnerException != null ? exception.InnerException.Message : exception.Message, TechnicalLog = exception.GetExceptionTechnicalInfo(), }); context.HttpContext.Response.StatusCode = (int)code; } context.ExceptionHandled = true; }
private async Task RespondWithValidationError(HttpContext context, ValidationException validationException, HttpStatusCode statusCode) { var apiErrorResult = ApiErrorResult.CreateFrom(validationException); await RespondWithError(context, apiErrorResult, statusCode); }
public void OnException(ExceptionContext context) { var exception = context.Exception; _logger.LogError( new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); if (context.Exception.GetType() == typeof(BusinessException) || context.Exception.GetType().BaseType == typeof(BusinessException)) { // handle bussiness exception var json = new ApiErrorResult { Success = false, ErrorCode = (context.Exception as BusinessException)?.ErrorCode, ErrorMessage = context.Exception.Message, }; context.Result = new BadRequestObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } else { // if it's not one of the expected exception, set it to 500 var code = HttpStatusCode.InternalServerError; switch (exception) { case EntityNotFoundException _: code = HttpStatusCode.NotFound; break; case ArgumentNullException _: code = HttpStatusCode.BadRequest; break; case InvalidArgumentException _: code = HttpStatusCode.BadRequest; break; case HttpRequestException _: code = HttpStatusCode.BadRequest; break; case UnauthorizedAccessException _: code = HttpStatusCode.Unauthorized; break; } context.Result = new ObjectResult( new ApiErrorResult { Success = false, ErrorCode = code.ToString(), ErrorMessage = exception.InnerException != null ? exception.InnerException.Message : exception.Message, TechnicalLog = exception.GetExceptionTechnicalInfo(), }); context.HttpContext.Response.StatusCode = (int)code; } context.ExceptionHandled = true; }
private static void SetResult(ActionExecutingContext context, string message) { var result = new ApiErrorResult <ApiError>(new ApiError(ApiErrorCodes.BadArgument, message)); context.Result = new BadRequestObjectResult(result); }
/// <summary> /// Handles a <see cref="ApiErrorResult"/> /// </summary> /// <param name="operationName">Operation that returned the result.</param> /// <param name="errorResult">The error object.</param> private static void HandleApiErrorResult(string operationName, ApiErrorResult errorResult) { HandleError(operationName, errorResult?.ErrorCode, errorResult?.Message); }
public void OnException(ExceptionContext context) { var exception = context.Exception; _logger.LogError( new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); ApiErrorResult apiErrorResult; if (context.Exception.GetType() == typeof(BusinessException) || context.Exception.GetType().BaseType == typeof(BusinessException)) { // handle bussiness exception apiErrorResult = new ApiErrorResult { Success = false, ErrorCode = context.Exception.GetType().Name, ErrorMessage = context.Exception.Message, }; context.Result = new BadRequestObjectResult(apiErrorResult); context.WithNotification("error", string.Empty, apiErrorResult.ErrorMessage); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } else { // if it's not one of the expected exception, set it to 500 var code = HttpStatusCode.InternalServerError; //TODO:Mapping if (exception is NotFoundExe) code = HttpStatusCode.NotFound; switch (exception) { case EntityNotFoundException _: code = HttpStatusCode.NotFound; break; case ArgumentNullException _: code = HttpStatusCode.BadRequest; break; case InvalidArgumentException _: code = HttpStatusCode.BadRequest; break; case HttpRequestException _: code = HttpStatusCode.BadRequest; break; case UnauthorizedAccessException _: code = HttpStatusCode.Unauthorized; break; } apiErrorResult = new ApiErrorResult { Success = false, ErrorCode = code.ToString(), ErrorMessage = exception.InnerException != null ? exception.InnerException.Message : exception.Message, TechnicalLog = exception.GetExceptionTechnicalInfo(), }; context.Result = new ObjectResult(apiErrorResult); context.WithNotification("error", string.Empty, "Đã có lỗi xảy ra. Vui lòng thử lại sau."); context.HttpContext.Response.StatusCode = (int)code; } context.ExceptionHandled = true; }
public override NotFoundObjectResult NotFound(object value) { return(base.NotFound(ApiErrorResult.NotFound(value))); }
public BadRequestObjectResult BadRequest(int status = StatusCodes.Status400BadRequest, params string[] messages) { return(base.BadRequest(ApiErrorResult.BadRequest(messages, status))); }
public override BadRequestObjectResult BadRequest(object value) { return(base.BadRequest(ApiErrorResult.BadRequest(value))); }
public NotFoundObjectResult NotFound(int status = StatusCodes.Status404NotFound, params string[] messages) { return(base.NotFound(ApiErrorResult.NotFound(messages, status))); }