I’m working on a class-based php web app. I have some places where objects are interacting, and I have certain situations where I’m using error codes to communicate to the end user — typically when form values are missing or invalid. These are situations where exceptions are unwarranted ( and I’m not sure I could avoid the situations with exceptions anyways).
In one object, I have some 20 code numbers, each of which correspond to a user-facing message, and a admin/developer-facing message, so both parties know what’s going on. Now that I’ve worked over the code several times, I find that it’s difficult to quickly figure out what code numbers in the series I’ve already used, so I accidentally create conflicting code numbers. For instance, I just did that today with 12, 13, 14 and 15.
How can I better organize this so I don’t create conflicting error codes? Should I create one singleton class, errorCodes, that has a master list of all error codes for all classes, systematizing them across the whole web app? Or should each object have its own set of error codes, when appropriate, and I just keep a list in the commentary of the object, to use and update that as I go along?
Edit: So I’m liking the suggestions to use constants or named constants within the class. That gives me a single place where I programatically define and keep track of error codes and their messages.
The next question: what kind of interface do I provide to the outside world for this class’ error codes and messages? Do I do something like triggerError(20) in the class, and then provide a public method to return the error code, the string constant, and the user- and admin-facing message?
You could create a couple of
definesto create named constants for all your error codes :And, then, use the constants in your code :
With that, nowhere in your code you’ll use the numerical value : everywhere *(except in the on and only file where you put the `define`s)*, you’ll use the codes.
It means :
Another idea could be to create a class to deal with errors :
And, then, use something like this :
Which one is *the best* ?
It’s probably a matter of personnal preferences… If you need to add some methods to deal with the errors, using a class might be useful. Else, defines are a great solution too.