Category : NetSuite ERP
When working with Map/Reduce (MR) scripts in NetSuite, one common challenge is handling the “Record has been changed” error. This error occurs when multiple processes or users attempt to update the same record simultaneously, leading to conflicts. To address this, you can implement a delay function that pauses execution, checks the elapsed time, and retries the operation. This strategy minimizes conflicts and ensures smoother script execution.
This error typically arises in scenarios where:
The solution involves introducing a retry mechanism with a delay, allowing the system to process other transactions before retrying.
A delay function ensures the script doesn’t immediately retry an operation when the error occurs. Instead, it:
Here’s how to create a delay function that checks the elapsed time and retries operations:
Date
object to track time and introduce pauses.try-catch
block to capture the “Record has been changed” error and invoke the delay function before retrying./** * Function to introduce a delay by checking elapsed time * @param {number} milliseconds - The desired delay in milliseconds */ function delay(milliseconds) { var startTime = new Date().getTime(); while (new Date().getTime() - startTime < milliseconds) { // Wait until the specified time has elapsed } }
/** * @NApiVersion 2.x * @NScriptType MapReduceScript */ define(['N/record', 'N/log'], function(record, log) { function map(context) { var recordId = context.value; var maxRetries = 5; // Maximum retry attempts var retryCount = 0; var delayTime = 2000; // 2 seconds delay while (retryCount < maxRetries) { try { // Load and update the record var rec = record.load({ type: 'customrecord_example', id: recordId, isDynamic: true }); rec.setValue({ fieldId: 'custrecord_status', value: 'Processed' }); rec.save(); log.debug('Record Updated Successfully', recordId); // Break out of the loop if successful break; } catch (e) { if (e.name === 'RECORD_CHANGED') { retryCount++; log.debug('Retry Attempt', retryCount); // Introduce a delay before retrying delay(delayTime); if (retryCount === maxRetries) { log.error('Max Retries Reached', `Record ID: ${recordId}`); throw e; } } else { // Log and throw non-related errors log.error('Unexpected Error', e); throw e; } } } } return { map: map }; });
The “Record has been changed” error is a common hurdle in NetSuite MR scripts, but it can be effectively managed with a delay function. By incorporating a retry mechanism with controlled delays, you ensure your scripts run reliably, even in high-volume or concurrent update scenarios. Implementing this solution not only minimizes conflicts but also improves overall script performance and system stability.
Tags: