3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonBoxでのエラー処理

Posted at

概要

PEPPERアプリを開発するときのエラー処理について
PythonBoxでハンドリングする方法のまとめめも。

弊社でやっているUtage Blogからの転用記事です。

エラー処理の方法

PythonBoxでエラーが発生した際、
ハンドリングしていないエラーの場合はアプリケーションが即座に終了します。

現状では、ロボットが強制終了した場合、
ユーザからはなんの前触れもなく突然終了したように見えてしまうので、
必ずハンドリングしてユーザに伝えるようにしましょう。

Choregrapheで検知できたエラーの場合は、
エラーが発生したボックスが赤くなります。
これはSyntaxErrorなどの場合でも同様です。

ss1.png

PythonBoxでエラーをハンドリングするためにはいくつかの方法がありますので、
それらの方法について解説していきます。

1. try, except

一般的なPythonでのエラー処理のように
try: except: で記述することでエラーをハンドリングできます。

class MyClass(GeneratedClass):
    def __init__(self):
        GeneratedClass.__init__(self)
 
    def onLoad(self):
        pass
 
    def onUnload(self):
        pass
 
    def onInput_onStart(self):
        try:
            raise Exception, "Raise Error."
        except Exception as e:
            self.log(str(e))
 
    def onInput_onStop(self):
        self.onUnload()
        self.onStopped()

上記の例では単純にログを吐いているだけなので、
なんのカバーもできてませんが、tryのなかでやっている処理で
例外が発生した場合でもアプリが落ちることはありません。

実際に使うケースだと下記のように使うことが多くなると思います。

class MyClass(GeneratedClass):
    def __init__(self):
        GeneratedClass.__init__(self)
 
    def onLoad(self):
        pass
 
    def onUnload(self):
        pass
 
    def onInput_onStart(self):
        try:
            # エラーが発生しうる処理
            self.onSucceeded()
        except Exception:
            self.onFailed()
 
    def onInput_onStop(self):
        self.onUnload()
        self.onStopped()

上のようにraiseされた場合の出力を変えてやることで
PythonBoxでエラーのハンドリングを行えます。

2. PythonBox標準の機能を使う

Boxを編集画面でonError出力を追加

ss2.png

ss3.png

このようにすると
PythonBoxで例外が発生した場合にonError出力から出力されるようになります。

class MyClass(GeneratedClass):
    def __init__(self):
        GeneratedClass.__init__(self)
 
    def onLoad(self):
        pass
 
    def onUnload(self):
        pass
 
    def onInput_onStart(self):
        raise Exception, "Raise Error."
 
    def onInput_onStop(self):
        self.onUnload()
        self.onStopped()

また、onErrorのTypeを文字列にすることで、
raiseしたExceptionのエラーメッセージなどの引数を文字列で出力することができます。

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?