0

In almost every kind of API there are integer error codes like (ex. 123) which indicates error type. I was wondering if it wasn't better to use descriptive string codes like user_not_found or invalid_request. In my opinion they are much more practical: let's say you get back to your code after months or so and you can easily go through error handling parts without searching for error codes in documentation.

Why integer error codes still exists in APIs?

keepkimi
  • 373
  • 3
  • 12

2 Answers2

2

In an API, clients are usually computers that test for response codes using conditions.

It is much faster to test agains integers than to test agains strings, that's all.

Moreover, error codes have a certain logic: APIs usually use HTTP codes, so when you (as a human) read them, you know that the 2xx indicate success, 4xx indicate client-side errors and 5xx indicate server-side errors, even if you don't know them all by heart.

EDIT:

Your question made me think about this answer, about how loading times in websites affect profits. You should read it to convince yourself that even a few milliseconds sometimes matter.

Community
  • 1
  • 1
alestanis
  • 21,519
  • 4
  • 48
  • 67
  • Yes, but in our times I don't think that comparison of two strings is really a matter. What do you think? – keepkimi Feb 18 '13 at 15:36
  • Comparing two strings is really much slower than comparing two integers, even nowadays. – alestanis Feb 18 '13 at 15:37
  • @keepkimi String comparisons will always be many magnitudes slower than comparing two integers (which often is a single CPU instruction). – Some programmer dude Feb 18 '13 at 15:38
  • I think it's a matter of microseconds so it's not a big problem. I think it's low price than saving developers' time for searching for what error code really mean. What do you think? – keepkimi Feb 18 '13 at 15:39
  • @alestanis thanks for performance link. I think I can't agree with it. Performance is one, but developers comfort in writing code is more important to me. I think similar example would be usage of ORM systems which are much slower than direct queries to DB but allow to keep code clean and easy to maintain. – keepkimi Feb 18 '13 at 15:51
  • I created a simple case comparing performance of integer vs string comparison: http://jsperf.com/integer-comparison-vs-string-comparison – keepkimi Feb 18 '13 at 15:51
  • @keepkimi I don't think your test is pertinent: you should compare strings with strings, knowing that your will surely have several error codes that start with the same letters (like "user" or "error" or "internal"). But it's a **very** good initiative. – alestanis Feb 18 '13 at 16:04
0

But there are nice names for most errors. Both standard C, POSIX and Windows have names for their error codes. Of course, most of these names are made as preprocessor macros, but there are also functions to get a nice string or message from these messages.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621