DEV Community

Discussion on: A better way to handle magic values and constants?

Collapse
 
avalander profile image
Avalander

As you say, integer values are hard to understand by humans and string values don't scale well, so, why not both? A simple way to improve it is to send the error code and an error message. The error code can still be used to handle the error programmatically, and the error message should give any humans reading it an approximate idea of what went wrong. As far as I know, that strategy is customary in several languages and frameworks.

Collapse
 
mjb2kmn profile image
MN Mark

You may be right and it's just that simple. Perhaps I am thinking too much in the context of Java which is usually about as human-friendly as a brick.

Collapse
 
avalander profile image
Avalander

Back in my days doing Java I used to create a custom exception class for about everything that could go wrong in the application, like PlayerNotFoundException, CommandExecutionFailedException, MissingFieldException, RedditIsDownException, you call it. In the exception message I would put what data caused the exception and, if applicable, how to correct it.

In the code, you can simply catch the type of exceptions you are interested and react accordingly, and when you read a stacktrace saying my.app.PlayerNotFoundException: couldn't find player with id '-1' it's quite easy to diagnose what went wrong.