Use cases for error codes

This is just a quick note regarding when you would use error or status codes. It’s here as a complimentary article to error handling.

Error / status codes are something you can return instead of an error value.

They are IDs, usually strings or numbers. The IDs denote particular states, such as success or a type of error. To see what the codes actually mean, you have to check some documentation where the IDs and errors are listed.

Here is a quick example:

let a;
let errno = 0;

function foo() {
  a = someFunctionCall();
  if (typeof a !== 'number') {
    errno = 1;
  }
}

function main() {
  foo();
  if (errno !== 0) {
    process.exit(errno);
  }
  console.log(`Program result is ${a}`);
}

They’re not really used except in rare cases. For example:

  • if your programming language doesn’t support error types
  • if you need to minimise memory usage in your program
  • if you need to communicate statuses to a different program, where you can only pass messages which are strings and not objects

Credits

Images:

  • Blue toy – Photo by Asdii Wang from Pexels
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments