/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
/**
 * @module lib/protect/errors/handler
 */

'use strict';

const _ = require('lodash');
const isContrastError = require('../../util/is-contrast-error');
const { KEYS, AsyncStorage } = require('../../core/async-storage');

/**
 * Adds an error handler on the domain we create to run source and sink
 * emits for protect.
 *
 * @param {AgentEmitter} emitter agentEmitter to handle error
 * @param {domain} domain to add error handler
 */
module.exports = function registerProtectErrorHandler(emitter, domain) {
  domain.on('error', function ProtectErrorCatch(error) {
    if (!isContrastError(error)) {
      const errorHandlers = domain._events.error;

      if (
        _.isArray(errorHandlers) &&
        _.last(errorHandlers).name !== 'ProtectErrorCatch'
      ) {
        // Allow other domains to run their catch handlers for error.
        return;
      }
      // Otherwise, throw out of our domain so we don't swallow it.
      throw error;
    }

    const res = AsyncStorage.fromException(error, KEYS.RES);
    const handled = emitter.handleError(error, res);

    if (!handled) {
      throw error;
    }
  });
};
