
【必見】「System.StringException: Invalid integer」エラーの修正方法
SalesforceのApexコードを実行する際に、「System.StringException: Invalid integer」というエラーが発生することがあります。このエラーは、文字列(String)を整数(Integer)に変換する際に、数値として認識できないデータが渡された場合 に発生します。
本記事では、このエラーの原因と、適切な修正方法について詳しく解説します。
1. エラーの概要
エラーメッセージ: "System.StringException: Invalid integer"
原因: String 型の値を Integer.valueOf() で変換しようとした際、数値以外の文字が含まれていた。
影響: Apexコードの実行が失敗し、データ処理が完了しない。
代表的なエラーケース
原因 例 文字列に数値以外の文字が含まれている Integer.valueOf("ABC123") 文字列が空またはnull Integer.valueOf("") or Integer.valueOf(null) 文字列に特殊文字が含まれている Integer.valueOf("10.5") or Integer.valueOf("10,000")
2. エラーが発生する主な原因
① 数値以外の文字が含まれている
"ABC123" のように、数値として認識できない文字が含まれていると変換エラーが発生。
② 空文字または null を変換しようとしている
Integer.valueOf("") や Integer.valueOf(null) を実行するとエラーになる。
③ Double 型や Decimal 型の文字列を Integer.valueOf() で変換しようとしている
"10.5" などの小数点を含む数値を Integer.valueOf() で変換するとエラーになる。
3. エラーを回避するための修正方法
① 文字列が整数値であることを事前チェックする
修正後のコード(正しい数値のみ変換)
public static Integer safeStringToInteger(String str) {
if (String.isEmpty(str) || !Pattern.matches('^[0-9]+$', str)) {
System.debug('Invalid input: ' + str);
return null; // エラーを防ぐためにnullを返す
}
return Integer.valueOf(str);
}
改善点: 正規表現 (^[0-9]+$) を用いて、入力が整数であるかを事前にチェックする。
② try-catch を利用してエラーハンドリングする
修正後のコード(例外処理を追加)
public static Integer convertStringToInteger(String str) {
try {
return Integer.valueOf(str);
} catch (Exception e) {
System.debug('Invalid integer format: ' + str);
return null; // エラー時はnullを返す
}
}
改善点: 例外が発生した場合に catch ブロックで適切に処理し、nullを返すことでシステムの安定性を向上。
③ Decimal や Double 型の数値を適切に変換する
NG例(小数点を含む数値をそのまま変換)
Integer i = Integer.valueOf("10.5"); // エラー発生!
OK例(Decimal型を使用して変換)
Decimal d = Decimal.valueOf("10.5");
Integer i = d.intValue(); // 正しく整数に変換
改善点: Decimal.valueOf() を使って Decimal 型に変換し、 intValue() で整数にする。
④ 数値フォーマット(カンマなど)を削除してから変換する
修正後のコード(カンマを削除)
public static Integer removeCommaAndConvert(String str) {
str = str.replace(',', '');
return Integer.valueOf(str);
}
改善点: カンマ区切りの数値 ("10,000") を Integer.valueOf() で処理できるように変換。
4. まとめ & Udemy・会社HPの紹介
「System.StringException: Invalid integer」エラーは、String 型のデータを Integer に変換する際に、数値として認識できないデータが含まれている場合に発生 します。入力値の事前チェック、try-catch の活用、小数点処理、フォーマット調整などを行うことで、エラーを回避できます。
🔹 Salesforceの詳細を学ぶならUdemy講座がおすすめ!
📌 Salesforce初級編:フローを使いこなして自動化を極めよう
https://www.udemy.com/course/salesforceflow/?referralCode=8F97869A4A6121086B88
📌 初心者向けSalesforce管理者ガイド:魅せるレイアウトで業務効率をアップしよう!
https://www.udemy.com/course/salesforce-basics-j/?referralCode=4200CF5D86BBE3ABF2D4
🔗 HPからご相談も可能
https://effinous.com/
さらに、無料でSalesforceのチェックリストを配布しています!Udemy講座を受講する前に、ぜひ「Salesforceフローの学習ロードマップ(PDF)」をダウンロードしてください。
Salesforceのデータ処理を適切に管理し、エラーを回避することで、業務の安定性と効率を向上させましょう!