I have a .net core api trying to implement it according to domain drive design principles.
In the domain layer there is a public Create
method that contains all validation and business rules. If one fails it will throw an exception. So basically you can not create an invalid entity or an invalid value type. For example:
public class Adult
{
private Adult(string name,int age)
{
this.Name = name;
this.Age = age;
}
public string Name { get; }
public int Age { get; }
public static Adult Create(string name, int age)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(nameof(name));
if (age < 18)
throw new ArgumentException("age should not be less that 18");
return new Adult(name, age);
}
}
In the web layer my web dtos have the basic validation attributes. For example:
public class AdultWebDto
{
[Required]
public string Name {get; set; }
public int Age {get; set; }
}
So basically if the user tries to create an adult with no name it will return a 400 Error but if he tries to create a user with an age less than 18 it will pass the dto validation and will return a 500 Error.
Of course if the user requests an Adult with either invalid name or invalid age it will return a 500 error since the data coming from the repository were invalid.
Is what I am doing right? So for simple validation rules to check that in the web layer and return a 400 error but in case of more complicated business rules to return a 500 error?