Comments (3)
Hi @akbarbd! 👋
from middleware.
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();
from middleware.
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)
- Disable ProblemDetailsResultFilter with condition like UseWhen (middleware) to support backwards compatibility HOT 1
- Does not work in .net 6 HOT 8
- `MapStatusCode` not respected for MVC validation errors HOT 1
- How can I use UseMemberCasing to serialize my data
- Ambiguous invocation in .Net 7 HOT 3
- Customize Exception Logging
- How to disable developer exception page middleware? HOT 3
- Issue with Serilog's RequestLogging and Rethrow HOT 8
- Changes in ASP.NET Core v7 HOT 3
- Master Branch not building in VS 2022 HOT 8
- ProblemDetailsMiddleware and DiagnosticListener.Write for handled exceptions
- [Feature request] ProblemDetails middleware allow send Detail property out of the box in Production HOT 2
- How to customise the ProblemDetails object when capturing FluentValidation exceptions? HOT 5
- Why are headers cleared at all by the middleware?
- ProblemDetails "Instance" property is not being set HOT 13
- How can I avoid returning internal class information in error?
- AddNewtonsoftJson and ProblemDetails using NET 6 HOT 1
- Add .NET 8 support for Authentication.JwtBearer.Google HOT 1
- [Feature request] Use custom mappers inside ProblemDetailsResultFilter
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from middleware.