0

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.

5
  • 7
    "my frontend partner can't take the error messages from format like that" - Why not? If they're able to access the data in the latter JSON structure, what prevents them from accessing the data in the former JSON structure? It seems like solving that problem would be the better approach. What you're suggesting instead is probably going to involve replacing the data annotations with your own custom validation. (And, incidentally, is providing less information about the problem to the client.) Commented Oct 3 at 12:46
  • error message it this way that'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 decision Commented Oct 3 at 12:52
  • If they want to return only the first error, all they have to do is to use Object.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 name Commented Oct 3 at 12:56
  • couldn'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 Commented Oct 3 at 13:01
  • BTW various JavaScript frameworks know how to handle the standard ProblemDetails report and display errors. You'll lose all that if you use a custom response Commented Oct 3 at 13:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.