0

I developing in ibm-app-conect and I have a problem.

I consume a backend soap service and transform it to JSON.

When I test my service (OK) I have no problem, but when I test my service with error cases I get a generic error message.

In that image I received the generic error message.

How could I control this error so that I get the following message that I show in the image?

Here is the code that I am using for this gatewayscript or program.

  var apim=require('apim');

  // IMPORT
  const transform = require('transform');
  const converter = require('json-xml-converter');

  // CONSTANTES
  const HTTP_CODE_FUNCTIONAL = 209;
  const HTTP_CODE_OK = 200;
  const HTTP_CODE_500 = 500;
  const HTTP_MESSAGE_500 = 'Internal Server Error';
  const codeErrors = [500, 403, 503, 404];

  // VARIABLES
  let bodyProvider =  apim.getvariable('message.body');
  let httpCode = apim.getvariable('message.status.code');
  let backSideTransport = apim.getvariable('message.headers.X-Backside-Transport');

  console.log("probando:" + backSideTransport);

  // SERVICE VARIABLES
  let tagBackend = '//xmlns:GetClienteObservadosOFACR1SelResponse';
  let tagNamespace = 'http://tempuri.org/';
  let dataType = 'xml';
  let nsVar = 'xmlns';

  // INIT VALIDATE PROCCESS
  manageResponse(httpCode,bodyProvider,dataType,tagBackend,nsVar,tagNamespace);


/*---------------------------- Operation section ----------------------------*/

// Especific function: Validate items ok
function validateEspecific(sJson) {

  let okSrvCods = ['OK'];
  let flagMapInGateway = true;
  let texto = '';   
  
  if (typeof sJson.GetClienteObservadosOFACR1SelResponse.GetClienteObservadosOFACR1SelResult.NewDataSet.Datos == undefined
   || sJson.GetClienteObservadosOFACR1SelResponse.GetClienteObservadosOFACR1SelResult.NewDataSet.Datos == null
   || sJson.GetClienteObservadosOFACR1SelResponse.GetClienteObservadosOFACR1SelResult.NewDataSet.Datos == '') {
        texto += '{ "blackListFlag": "false"}';
    }else{
        texto += '{ "blackListFlag": "true"}';
    }
    generateResponseMessage(200,'OK','0','EJECUCION CON EXITO','0000', 'OK',texto);
  
}

// Especific function: Create response 200
function mapJsonOK(codError, msgError, respuesta) {
    let rsMessage = '{  "sequenceId":  "' + respuesta.trim() + '"}';
    generateResponseMessage(200,'OK','0','EJECUCION CON EXITO',codError, msgError,rsMessage);
}

/*---------------------------- Operation section ----------------------------*/

/*------------------------------ Free section -------------------------------*/
function defaultVal(field, def) {
    field = typeof field !== 'undefined' && field != null && field != '' ? field : def;
    return field;
}
/*------------------------------ Free section -------------------------------*/

/*-------------------------- Framework IFX section --------------------------*/

//Generic function: Manage response
function manageResponse(httpCode,bodyProvider,dataType,tagBackend,nsVar,tagNamespace){
    
  if (codeErrors.includes(httpCode)){
      // Separar segun codigo
      generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');
  }else if(200 == httpCode){

      if(bodyProvider){
                    validateAndTransformBody(dataType, bodyProvider, tagBackend, nsVar, tagNamespace);
      }else{
          generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');
      }
  }else{
      // Codigo HTTP no conocido, genera respuesta generica
      generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');
  }
  
}

// Generic function: Validate dataType and transform body
function validateAndTransformBody(dataType,bodyProvider, tagBackend, nsVar, tagNamespace) {

    if(dataType == 'xml' ){
  
    let options = { 'expression': '//tns1:GetClienteObservadosOFACR1SelResponse', 'xmldom': bodyProvider, 'namespace': { 'tns1' : 'http://tempuri.org/'}};  
    let option = { omitXmlDeclaration: true };

    transform.xpath(options, function(err, xmlNodeList) {
        if (err) { session.output.write(err);
      }else{

        let output = XML.stringify(option, xmlNodeList);
        let xml = XML.parse(output);
        let sJson = converter.toJSON('badgerfish',xml);
        validateEspecific(sJson);

      }
    });
  
  }else{ validateEspecific(bodyProvider); }
  
}

// Generic function: Propagate to Map Policy
function skipToMap(flag) {
    apim.setvariable('message.headers.skip', true);
}

// Generic function: Responde cabecera de error IFX
function generateResponseMessage(codeHttp,reasonHttp,busResponseCode,busResponseMessage,srvResponseCode,srvResponseMessage,responseMessage){
    
    let globalTransaccionId = apim.getvariable('message.headers.X-Global-Transaction-ID');
    
    apim.setvariable('message.headers','','clear');
    apim.setvariable('message.body','','clear');
    
    apim.setvariable('message.headers.busResponseCode', busResponseCode);
    apim.setvariable('message.headers.busResponseMessage', busResponseMessage);
    apim.setvariable('message.headers.srvResponseCode', srvResponseCode);
    apim.setvariable('message.headers.srvResponseMessage', srvResponseMessage);
    apim.setvariable('message.headers.X-Global-Transaction-ID', globalTransaccionId);
    
    if(responseMessage != null){
        apim.setvariable('message.body', responseMessage);
    }
    
    apim.setvariable('message.status.code', codeHttp);
    apim.setvariable('message.status.reason', reasonHttp);
    apim.output('application/json');
    
}


/*-------------------------- Framework IFX section --------------------------*/

function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }

I try to use the header X-Backside-Transport but I couldn't fix it.

if (codeErrors.includes(httpCode)){

let backSideTransport = apim.getvariable('message.headers.X-Backside-Transport');
      // Separar segun codigo
      generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');


  }else if(200 == httpCode && backSideTransport == 'FAIL FAIL'){

          generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '502','An error occurred trying to  invoke external services.');
     apim.setvariable('message.headers.srvResponseCode', HTTP_CODE_500);
     apim.setvariable('message.headers.srvResponseMessage', HTTP_MESSAGE_HTTP_500);
      }else{
          generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');
      }
  }else{
      // Codigo HTTP no conocido, genera respuesta generica
      generateResponseMessage(HTTP_CODE_500, HTTP_MESSAGE_500, '302','An error occurred trying to invoke external services.');
  }
}
user16217248
  • 3,119
  • 19
  • 19
  • 37

1 Answers1

0

To control SOAP error messages in JavaScript if the HTTP code is 200, you can use the XMLHttpRequest (XHR) object to make an HTTP request and handle the response. Here's an example code snippet:

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) { // Request finished and response is ready
    if (xhr.status === 200) { // HTTP OK
      // Handle successful response
      const soapResponse = xhr.responseXML;
      // ...
    } else {
      // Handle HTTP error
      console.error(`HTTP error ${xhr.status}: ${xhr.statusText}`);
    }
  }
};

xhr.open("POST", "https://example.com/soap-endpoint");
xhr.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
xhr.send(soapRequest);

In the above code, we're creating a new instance of the XHR object, setting its onreadystatechange property to a function that will handle the response when the request is finished and the response is ready. Inside the onreadystatechange function, we're checking if the readyState property of the XHR object is equal to 4 (meaning the request is finished and the response is ready), and if the status property is equal to 200 (meaning the HTTP request was successful).

If the HTTP request is successful, we can handle the SOAP response using the responseXML property of the XHR object. If the HTTP request is not successful, we can handle the error by logging an error message to the console using console.error().