JavaScript More descriptive error codes

Download JavaScript for free

Example

In the event that geolocation fails, your callback function will receive a PositionError object. The object will include an attribute named code that will have a value of 1, 2, or 3. Each of these numbers signifies a different kind of error; the getErrorCode() function below takes the PositionError.code as its only argument and returns a string with the name of the error that occurred.

var getErrorCode = function(err) {
  switch (err.code) {
    case err.PERMISSION_DENIED:
      return "PERMISSION_DENIED";
    case err.POSITION_UNAVAILABLE:
      return "POSITION_UNAVAILABLE";
    case err.TIMEOUT:
      return "TIMEOUT";
    default:
      return "UNKNOWN_ERROR";
  }
};

It can be used in geolocationFailure() like so:

var geolocationFailure = function(err) {
  console.log("ERROR (" + getErrorCode(err) + "): " + err.message);
};
Global error handling in browsers