0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Salesforce DML処理における`as user`の例外動作について

Posted at

Salesforce DML処理におけるas userの例外動作について

概要

SalesforceでDML処理にas userキーワードを追加すると、失敗時に発生する例外の種類が変わります。

例外の違い

DML処理 失敗時の例外 getTypeName()の戻り値
通常のDML DmlException System.DmlException
as user Exception System.SecurityException

静的解析対応での障害

問題

静的解析ツールはFLS違反を検出するためas userの追加を推奨しますが、これにより既存のDmlExceptionでのエラーハンドリングが機能しなくなります。

// 変更前
try {
    insert record;
} catch (DmlException e) {
    // 重複エラー等の処理
    if (e.getDmlType(0) == StatusCode.DUPLICATE_VALUE) {
        // この処理が実行されない
    }
}

// 変更後(as user追加)
try {
    insert as user record;
} catch (DmlException e) {
    // このcatch文は実行されない
    // SecurityExceptionが発生するため
}

対処法

as user使用時はDmlExceptionが発生しないため、Exceptionのcatch文でエラーハンドリングを行います:

public static void safeInsert(SObject record) {
    try {
        insert as user record;
        
    } catch (Exception e) {
        // as user使用時はSecurityExceptionが発生
        if (e.getTypeName() == 'System.SecurityException') {
            // エラーメッセージから元のDMLエラー種別を判定
            String errorMessage = e.getMessage();
            
            if (errorMessage.contains('DUPLICATE_VALUE')) {
                // 重複エラーの処理(元の処理と同じ)
            } else if (errorMessage.contains('REQUIRED_FIELD_MISSING')) {
                // 必須フィールドエラーの処理(元の処理と同じ)
            } else {
                // 権限不足エラーの処理
            }
        } else {
            throw e;
        }
    }
}

まとめ

  • as user使用時はSecurityExceptionが発生
  • 静的解析対応時は既存の例外処理が機能しなくなる
  • Exceptionのcatch文でエラーメッセージを解析して元のエラーハンドリング動作を維持
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?