I'm using data annotations from System.ComponentModel.DataAnnotations in my ASP.NET project. I get an error message where you can describe the requirements such as "Name is required" and etc.
My problem is that it returns error message it this way (taken from Swagger):
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Name": [
"Name is required"
],
"MinistryCode": [
"Ministry code is required"
]
},
"traceId": "00-f9bbded6caac557dfeb3d93d3ec99362-8b288742231f76ec-00"
}
But since my frontend partner can't take the error messages from format like that he asked me to return it in one string, something like this:
{
"error": "Name is required"
}
I have been searching for answer online but couldn't really find something matching.
error message it this waythat's an official standard, RFC9457 first introduced as RFC7808 in 2016. The best option is to tell your partner to fix their code. All they have to do is parse this JSON string and show what they want. As you just showed there can be multiple error messages. The API can't decide that only the first should be shown, that's 10000% a UI decisionObject.values(err.errors)[0]to get the first error. The standard is way better though. It tells you what field failed and why. No need to parse to get the field namecouldn't really find something matching.that's shown in the official docs: Handle errors in ASP.NET Core APIs. This shows how to customize the response too. Check this blog post too which shows various ways to customize the output