I'm trying to build an alternative of ModelState as when I return this from api like return BadRequest(ModelState)
it doesn't have much information other than somethings gone wrong with the request. So I have decided to build an alternative which will eventually look like this:
{
"code": 1000,
"message": "Invalid request",
"fields": [
{
"name": "Password",
"message": "Password does not meet complexity requirements."
}
]
}
In order to accomplish this, I have the following models in my api project:
ErrorResponse.cs:
public class ErrorResponse
{
public string Code { get; set; }
public string Message { get; set; }
public Dictionary<string, Field> Fields { get; set; }
}
Field.cs:
public class Field
{
public string Name { get; set; }
public string Message { get; set; }
}
Thanks to using FluentResults
I can determine the error from the service layer within my controller like so:
if (result.HasError<PasswordError>())
{
}
However I've realised that I now need to return the ErrorResponse
but each Field
has a name and the only way to know the name of the field is through the controller using:
nameof(RegisterRequest.Password)
Is there a way to do this in a clean generic way without using magic strings?