dev-mastery / comments-api

MIT License
1.92k stars 649 forks source link

How to support api error codes and subcodes #51

Open moamen-nour opened 3 years ago

moamen-nour commented 3 years ago

Hi, first of all thanks a lot for your video explaining clean architecture and the example service. It really was of great help. I have a question on my mind, how to support api error responses with attached error codes and subcodes without allowing the usecase to know which http status and error codes | subcodes returned through the api. The first option that came to my mind is to create custom errors for the usecases to throw and in the controller layer I would map those errors to http status codes and service error codes. The second option is to store the mapping within the custom error.

If the first option is viable should the mapping be based on error messages or error types. Thank you.

arcdev1 commented 3 years ago

The first approach is the cleanest. The entities and use cases shouldn't know or care about HTTP. Base the mapping on Error types, not messages, since the message is more likely to change. In general, I would have a few base CustomError types and map those to status codes using instanceof. Usually, the main ones we really care about in code are 400, 403, and 500 the rest tend to be handled by middleware running outside our code.