Hacker News new | ask | show | jobs
by b-pagis 1557 days ago
Such simple approach is limited only to errors without arguments.

For more complex use cases, where we would want an error message to indicate that field value was too long and in addition provide maximum field length, we would need to introduce new field in the error response.

While it is solvable by adding this information to client application side. It would create a situation where the logic is duplicated in two places (backend and client application)...

Also if we would want better UX, then we would need to display all errors at the same time in the form that is incorrectly filled. This would require changing error structure to return array of errors and it potentially create a breaking change in the API or would result in confusing structure that supports both, legacy and new format...

Some years ago, I wrote an article sharing the ideas on how REST API error structuring could be done depending on the complexity of application or service: https://link.medium.com/ObW78jhDkob

1 comments

Interesting! Do you find that returning an array of errors works in practice?

Most validation I’ve seen looks like:

    raise error if foo
    raise other_error if bar
This pattern turns into one exception per response, and some foresight in architecting exceptions would be needed
From my experience it serves very well for validating inputs of large forms - e.g. loan application, international payments, etc.

If you need to validate some business logic like if sender's account has funds and receiver's account is not blocked, then this approach starts to look a bit strange. I would guess that the most of the time developers would implement checks so they would fail on first condition and would not check later one. This would result with single error in the array that kinda would look strange.

Validating business logic and returning several errors at the time requires good knowledge of the domain and in depth design of the system you are working. As this creates more complexity and slows down delivery, most of the time it is ditched and used only for particular use cases.

We could say that this would be more applicable to corporate solutions, but IMHO it really depends of the scale of the project, man power and the user experience you would want to create.

The Phoenix framework does this for forms. It requires a whole system built around a type called a Changeset that describes input parameters, their validity, and how to modify a struct to reflect the valid changes. In practice this ends up tightly coupled to the database layer for simplity.
Does "tightly coupled with the database" work, in practice?
It's only tightly coupled if you let it be. You can create changesets around any data shape, whether thats connected to your schema' table, a partial view of a table or entirely independent.