Skip to content

構造化処理のエラーハンドリング

RDEのエラーコードとメッセージ

RDEのエラーコードとメッセージは、job.failedというテキストファイルへ出力することで終了コード0以外をリターンすることで、構造化処理の異常終了をRDEアプリケーションから確認可能です。

フォーマット

1
2
ErrorCode=<エラーコード・番号>
ErrorMessage=<エラーメッセージ>

jobs.faildの記述例

1
2
ErrorCode=1
ErrorMessage=ERROR: failed in data processing

error

RDEToolKitを使ってエラーハンドリングを実装する

RDEToolKitでは、rdetoolkit.workflows.run()を利用することで、内部で発生した例外rdetoolkit.exceptions.StructuredErrorをキャッチすることが可能です。例えば、下記の例では、存在しないファイル読み込んだときのエラーを、job.failedに記述する例です。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# main.py
import json

import rdetoolkit
from rdetoolkit.exceptions import StructuredError


def read_experiment_data(config_path: str) -> dict:
    with open(config_path, "r") as f:
        return json.load(f)


def dataset(srcpaths, resource_paths):
    try:
        config = read_experiment_data("not_found_file_path.txt")
    except FileNotFoundError as e:
        # Add the error message and the error code
        raise StructuredError("Config file not found", ecode=3, eobj=e) from e

    # Do something with the dataset
    pass


if __name__ == "__main__":
    rdetoolkit.workflows.run(custom_dataset_function=dataset)

job.failedの出力結果は以下のようになります。

1
2
ErrorCode=3
ErrorMessage=Config file not found

スタックトレース整形する

rdetoolkit.errors.catch_exception_with_messageを使用すると、構造化処理のスタックトレースを整形することが可能です。例えば、上記のdatasetに、catch_exception_with_messageでデコレーターとして付与します。

デコレータを使用すると、スタックトレースの整形、エラーメッセージ、エラーコードの上書き、デフォルトのスタックトレースの表示・非表示を設定できます。

  • error_message: 上書きするエラーメッセージ
  • error_code: 上書きするエラーコード
  • verbose: デフォルトのスタックトレースの表示・非表示
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@catch_exception_with_message(error_message="Overwrite message!", error_code=100, verbose=False)
def dataset(srcpaths, resource_paths):
    try:
        config = read_experiment_data("not_found_file_path.txt")
    except FileNotFoundError as e:
        # Add the error message and the error code
        raise StructuredError("Config file not found", ecode=3, eobj=e) from e

    # Do something with the dataset
    passs

この時のスタックトレースは、以下の通りです。

1
2
3
4
5
6
7
8
Traceback (simplified message):
Call Path:
   File: /Users/myproject/container/modules/custom_modules.py, Line: 109 in wrapper()
    └─ File: /Users/myproject/container/main.py, Line: 27 in dataset()
        └─> L27: raise StructuredError("Config file not found", ecode=3, eobj=e) from e 🔥

Exception Type: StructuredError
Error: Config file not found

また、デコレーターを使用する場合のjob.failedは、デコレータを付与する前と同様の出力となります。これは、内部で明示的に定義したraise <例外クラス>の内容を捕捉し、詳細情報をjob.faildに書き込みます。

デコレーターを付与した関数内部で明示的に定義した例外クラスでエラーを捕捉した場合、その例外情報が優先されるため、デコレータ引数で与えたメッセージやエラーコードでは上書きされません。

このデコレータを使用すると、事前に例外処理を定義していないかつ、予期しないエラーが発生し捕捉したとき、デコレータの引数で事前に定義したエラーメッセージとエラーコードをjob.faildに書き込むことができます。

1
2
ErrorCode=3
ErrorMessage=Error: Config file not found

もし、デコレータを使わなず、予期しないエラーが発生した場合、job.faildには以下のデフォルトメッセージが書き込まれます。そのため、Web UIで確認したとき、エラーの特定が難しいです。

1
2
ErrorCode=999
ErrorMessage=Error: Please check the logs and code, then try again.