Reputation: 3769
I work on a project target windows phone 7.5 and above.
I fetch data from the server using Rest API, when an error occurred, the server will return me a error message, the message json contains 2 parts, one part is a error code(int), one part is the error message(string)
What I want is refer the error code, and display a DIY error message(I do not want to use the error message from the server).
So what I do is declare a static dictionary, and put the error code as the key and my error message as the value. So I can refer the message easily.
There are nearly 90 errors.
Is there any better way to solve this? Will it cause any performance issue via what I do?
Upvotes: 2
Views: 72
Reputation: 35925
Once you get your error handling going. The next step would possibly be to simplify the displayed errors. Your user probably doesn't need to know about all 90 types of the errors, plus this increases attack plain on the server.
What you can do is to group error codes and display only general info (based on the fab Jon's code)
class Program
{
public static readonly Dictionary<IEnumerable<int>, string> ErrorMessages =
new Dictionary<IEnumerable<int>, string>
{
{ Enumerable.Range(0,10), "Your frobinator was jamified" },
{ Enumerable.Range(10,10), "The grigbottle could not be doxicked" },
{ Enumerable.Range(20,10), "Ouch! That hurt!" },
{ Enumerable.Range(30,10), "The input was not palendromic" },
// etc
};
static void Main(string[] args)
{
int error = 2;
string message = ErrorMessages
.Where(m => m.Key.Contains(error))
.FirstOrDefault().Value;
Console.WriteLine(message); // "Your frobinator was jamified"
}
}
This solution is O(N)
, whereas Jon's is O(1)
. But on the scale you work O(N) ~ O(1)
, as all data is in fast memory and the number of elements in the collection is small.
Upvotes: 0
Reputation: 1502376
Well personally I'd probably put them in a file of some description - either a resource file or a custom embedded resource you can load. That lends itself to i18n, and keeps your source code full of source rather than data.
But if you really want to include the data in the code, you can easily create a dictionary with the values specified in a collection initializer:
public static readonly Dictionary<int, string> ErrorMessages =
new Dictionary<int, string>
{
{ 0, "Your frobinator was jamified" },
{ 1, "The grigbottle could not be doxicked" },
{ 35, "Ouch! That hurt!" },
{ 14541, "The input was not palendromic" },
// etc
};
Upvotes: 1