DEV Community

Discussion on: Writing REST API error handling my way ?

Collapse
 
rhymes profile image
rhymes

I don't use a specific format. In one API I'm using Govalidator that returns errors like:

{
    "username": "Your username needs to be at least 6 characters.",
    "password": "Password is not a valid password"
}

The title of the error might be redundant. You already know you have a validation error for the username because the username is present in the response.

Also "errors" is probably redundant (HTTP already tells you the request failed) but we could keep it there nonetheless.

If you want to return multiple errors for a single field why not just:

{
  "username": ["Your username needs to be at least 6 characters.", "Do not use admin :D"]
}
Collapse
 
coolgoose profile image
Alexandru Bucur

I agree with you, and that's how most of the time I was doing my API replies. I was mostly curious on why people are doing it differently.

One explanation on why it's better to have an array of objects is that it's easier to map the response in strong typed languages like java or c#.

Collapse
 
rhymes profile image
rhymes

I guess. I've never used JSONApi so I can't comment on that either. I'm definitely, sadly, in the RESTish camp.

Thread Thread
 
coolgoose profile image
Alexandru Bucur

Technically JSON API is rest, let's say just a bit more structured.