'Assign an error type to each FluentValidation rule .net c#
I am working on fluent validation which will generate custom api response
I am able to add ErrorCode and ErrorMessage in the rules. But I also need to assign a type to each rule.
Below are the rules:
RuleFor(x => x.Name).Must(ValidateUniqueName).WithErrorCode("0001").WithMessage("Name should be unique");**type1**
RuleFor(x => x.Address).Must(ValidateValidAddress).WithErrorCode("0002").WithMessage("Address is invalid");**type2**
Now I am categorizing these rules into different types because UI has to implement/show the rule's error messages in different ways thats why assigning different types to each rules. For example rule one is of type type1 and rule 2 is of type type2
Below is the my error class
public class ApiError
{
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public string PropertyName { get; set; }
public ErrorType ErrorType { get; set; }
}
public enum ErrorType
{
type1,
type2
}
Validator code
public List<ApiError> Validate<T1, T2>(T1 modelValidator, T2 modelToBeValidated, bool isPropertyNameRequired = false)
where T1 : IValidator<T2>
where T2 : class
{
List<ApiError> errors = new List<ApiError>();
var validationResult = modelValidator.Validate(modelToBeValidated);
foreach (var validationFailure in validationResult.Errors)
{
var error = new ApiError
{
ErrorCode = validationFailure.ErrorCode,
PropertyName = isPropertyNameRequired ? validationFailure.PropertyName : null
};
error.ErrorType = ??
error.ErrorDescription = validationFailure.ErrorMessage;
errors.Add(error);
}
return errors;
}
Now how can I send types as well along with errorcode and errormessage? Any help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
