How to handle errors when using NSRange

I keep getting a series if errors in the console when using NSRange in a bit of code that parses OFX financial data.

These are typical:

*** -[NSCFString substringToIndex:]: unable to set argument 2 because the AppleScript value <NSAppleEventDescriptor: 9.22337e+18> could not be coerced to type Q.

The code I am using is a repeat loop. I exit the repeat loop using the ranges length and the error is generated.


		set tDataStr to tOFXData
		set tTag to NSString's stringWithString_("<STMTTRN>")
		
		repeat
			
			--READS THE TRANSACTION
			set tRange to tDataStr's rangeOfString_(tTag)
			if tRange's |length| = 0 then exit repeat
			set tStart to (tRange's location) + (tRange's |length|)
			set tTempStr to tDataStr's substringFromIndex_(tStart)
			set tRange to tTempStr's rangeOfString_(tTag)
			set tEnd to (tRange's location) - 1
			set tTransactionStr to tTempStr's substringToIndex_(tEnd)
			--	log tTransactionStr
			
			
			
			set tTransLen to tTransactionStr's |length| as integer
			set tTagLen to tTag's |length| as integer
			set tOffset to tStart + tTransLen + tTagLen
			
			--	log tOffset
			
			set tDataStr to tDataStr's substringFromIndex_(tOffset)
			
			
			
			--NOW GET EACH ITEM FROM THE TRANSACTION
			set tTransactionType to readFirstOFXTag(tTransactionStr, "<TRNTYPE>")
			log tTransactionType
			set tTransactionDatePosted to readFirstOFXTag(tTransactionStr, "<DTPOSTED>")
			log tTransactionDatePosted
			set tTransactionAmount to readFirstOFXTag(tTransactionStr, "<TRNAMT>")
			log tTransactionAmount
			set tTransactionUniqueID to readFirstOFXTag(tTransactionStr, "<FITID>")
			log tTransactionUniqueID
			set tTransactionName to readFirstOFXTag(tTransactionStr, "<NAME>")
			log tTransactionName
			
		end repeat

Anyone got any ideas?

Thanks

Terry

First, when an error says there’s a problem with argument n, it’s actually a problem with argument n-1.

You need to add a second check for |length| of when you get rangeOfString_ a second time. What you’re seeing is that when there are no more substrings to be found, the range is {NSNotFound, 0}, and NSNotFound is defined as NSIntegerMax, which is out of the range of AS’s integers (way our, in 64-bit land).

The bottom line is that you should always check the length first.

Thanks Shane.