// This will map Exceptions to the corresponding Conflict status code. private void _configureExceptionProblemDetails(ProblemDetailsOptions options) { options.Map <EntityNotFoundException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status404NotFound)); options.Map <NotImplementedException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status501NotImplemented)); options.Map <HttpRequestException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status503ServiceUnavailable)); options.Map <UnauthorizedAccessException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status403Forbidden)); options.Map <EntityTagMismatchException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status412PreconditionFailed)); options.Map <OptimisticConcurrencyException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status409Conflict)); options.Map <SqlException>(ex => SqlExceptionHandler.IsPrimaryKeyOrUniqueKeyViolation(ex) ? new ExceptionProblemDetails(ex, StatusCodes.Status409Conflict) : new ExceptionProblemDetails(ex, StatusCodes.Status500InternalServerError)); options.Map <FluentValidation.ValidationException>(ex => new FluentValidationProblemDetails(ex, StatusCodes.Status400BadRequest)); }
public override void OnException(ExceptionContext context) { _log(context); var message = context.Exception.Message; IActionResult result = null; switch (context.Exception) { case UnauthorizedAccessException ex: { result = new ObjectResult(new { ErrorMessage = message }) { StatusCode = 403 }; break; } case EntityNotFoundException ex: { result = new NotFoundObjectResult(message); break; } case EntityTagMismatchException ex: { result = new StatusCodeResult(412); break; } case OptimisticConcurrencyException ex: { result = new ObjectResult(new { ErrorMessage = message }) { StatusCode = 409 }; break; } case FluentValidation.ValidationException ex: { var msd = new ModelStateDictionary(); foreach (var error in ex.Errors) { string key = error.PropertyName; msd.AddModelError(key, error.ErrorMessage); } result = new BadRequestObjectResult(msd); break; } case SqlException ex: { if (SqlExceptionHandler.IsPrimaryKeyOrUniqueKeyViolation(ex)) { result = new ObjectResult(new { ErrorMessage = message }) { StatusCode = 409 }; } break; } } if (result != null) { if (result is ObjectResult o) { o.ContentTypes.Clear(); o.ContentTypes.Add("application/json"); } context.Result = result; context.Exception = null; } base.OnException(context); }