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?

try except raiseを使った例外エラー処理

Posted at

まずtryで例外が発生するかもしれない処理を書いてあげる
そして例外エラーが発生したらexceptで受け止めてあげて別の処理を行う
そしてraiseは意図的に例外エラーを発生させる。そしてそのエラーに名前を付けられる
すると名付けたエラーをexceptでエラー名を受け取ることでエラー別の処理が可能となる

サンプルコード

@app.route('/add_employee', methods=['POST'])
def add_employee():
    data = request.get_json()
    try:
        # データ型のチェック
        if not isinstance(data['id'], int):
            raise ValueError('ID must be an integer')
        if not isinstance(data['name'], str):
            raise ValueError('Name must be a string')
        
        # データの挿入
        insert_employee(data['id'], data['name'])
        return jsonify({"message": "Employee added successfully"}), 200

    except (KeyError, ValueError) as e:
        return jsonify({"error": str(e)}), 400

    except sqlite3.IntegrityError as e:
        return jsonify({"error": "Database integrity error"}), 400

    except Exception as e:
        return jsonify({"error": "An unexpected error occurred"}), 500
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?