/**
 * Build a cartoError from a generic error
 * @constructor
 * 
 * @return {CartoError} A well formed object representing the error.
 */
function CartoError (error) {
  if (_isWindshaftError(error)) {
    this.message = error.errors[0];
    return this;
  }
  if (error && error.message) {
    this.message = error.message;
    return this;
  }
  if (error && error.responseText) {
    this.message = _handleAjaxResponse(error);
    return this;
  }

  this.message = 'unexpected error';
}

function _isWindshaftError (error) {
  return error && error.errors_with_context;
}

function _handleAjaxResponse (error) {
  try {
    var parsedError = JSON.parse(error.responseText);
    return parsedError.errors[0];
  } catch (exc) {
  }
}

module.exports = CartoError;

/**
 * 
 * Represents an error in the carto library.
 * 
 * Some actions like adding a layer to a map will trigger a **reload cycle**
 * if some error happens during this reload cycle will be captured and transformed into a 
 * `CartoError`.
 * 
 * The cartoErrors can be obtained listening to the client {@link carto.events|error events} `client.on(carto.events.ERROR, callback);` 
 * or through the promise returned by each async action.
 * 
 * @example
 * // Listen when a layer has been added or there has been an error.
 * client.addLayer(layerWithErrors)
 *  .then(()=> console.log('Layer added succesfully'))
 *  .catch(cartoError => console.error(cartoError.message))
 * 
 * @example 
 * // Events also will be registered here when the map changes.
 * client.on(carto.events.SUCCESS, function () {
 *  console.log('Client reloaded');
 * });
 * 
 * client.on(carto.events.ERROR, function (clientError) {
 *  console.error(clientError.message);
 * });
 * 
 * @typedef CartoError
 * @property {string} message - A short error description.
 * @api
 */

@@ -1,12 +1,56 @@
+var UNEXPECTED_ERROR = 'unexpected error';%0A%0A
 /**%0A * Build
@@ -508,34 +508,32 @@
 ssage = 
-'unexpected error'
+UNEXPECTED_ERROR
 ;%0A%7D%0A%0Afun
@@ -653,16 +653,42 @@
 rror) %7B%0A
+  var errorMessage = '';%0A%0A
   try %7B%0A
@@ -745,22 +745,30 @@
 t);%0A    
-return
+errorMessage =
  parsedE
@@ -803,17 +803,87 @@
 xc) %7B%0A  
-%7D
+  // Swallow parse error%0A  %7D%0A  return errorMessage %7C%7C UNEXPECTED_ERROR;
 %0A%7D%0A%0Amodu

Handle AJAX errors better