Code Monkey home page Code Monkey logo

Comments (3)

khellang avatar khellang commented on June 8, 2024

Hi @akbarbd! 👋

See https://github.com/khellang/Middleware/blob/master/samples/ProblemDetails.Sample/ProblemDetailsOptionsExtensions.cs

from middleware.

akbarbd avatar akbarbd commented on June 8, 2024

I am develop this way but multiple error is not showing and output is unreadable exception.

1 . Exception Inheritance Class

 public class ValidationException : Exception
{
    public IDictionary<string, string[]> Errors { get; } 
    public ValidationException(string message, int? code = null) : base(message, code: code)
    {
        Errors = new Dictionary<string, string[]>();
    }

    public ValidationException(IEnumerable<ValidationFailure> failures):this("One or more validation failures have occurred.")
    {
        Errors = failures
            .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
            .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
    }
}

2. MediatR Pipeline Behavior

 public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
   where TRequest : class, IRequest<TResponse>
  {
      private readonly IEnumerable<IValidator<TRequest>> _validators;
      private readonly IServiceProvider _serviceProvider;

      public ValidationBehavior(IServiceProvider serviceProvider, IEnumerable<IValidator<TRequest>> validators)
      {
          _serviceProvider = serviceProvider;
          _validators = validators;
      }
      public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
      {
          if (_validators.Any())
          {
              var context = new ValidationContext<TRequest>(request);

              var validationResults = await Task.WhenAll(
                  _validators.Select(v =>
                      v.ValidateAsync(context, cancellationToken)));

              var failures = validationResults
                  .Where(r => r.Errors.Any())
                  .SelectMany(r => r.Errors)
                  .ToList();

              if (failures.Any())
                  throw new ValidationException(failures);
          }
          return await next();
      }
  }

3. ProblemDetailsExtensions

     public static IServiceCollection AddCustomProblemDetails(this IServiceCollection services)
      {
          services.AddProblemDetails(x =>
          {
               x.IncludeExceptionDetails = (ctx, _) =>
              {
                  // Fetch services from HttpContext.RequestServices
                  var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
                  return env.IsDevelopment() || env.IsStaging();
              };
           
            // Exception will produce and returns from  FluentValidation RequestValidationBehavior
            x.Map<ValidationException>(ex => new ProblemDetailsWithCode
            {
                Title = "input validation rules broken",
                Status = (int)ex.StatusCode,
                Detail = ex.Message,
                Type = "https://somedomain/input-validation-rules-error", 
            });
          
        });
        return services;
    }

4. Startup
builder.Services.AddCustomProblemDetails();
app.UseProblemDetails();

validation error

from middleware.

khellang avatar khellang commented on June 8, 2024

I am develop this way but multiple error is not showing

I don't see you pulling out the Errors from the ValidationException and mapping it onto the ProblemDetailsWithCode class anywhere?

and output is unreadable exception

If you want to turn off the exception details, you just need to return false from your IncludeExceptionDetails hook.

from middleware.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.