-
-
Notifications
You must be signed in to change notification settings - Fork 122
Feature/centralized error handling #182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aneesafatima
wants to merge
4
commits into
AOSSIE-Org:main
Choose a base branch
from
aneesafatima:feature/centralized-error-handling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| .qodo | ||
| .env |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class MissingFieldError(Exception): | ||
| """Exception raised when a required field is missing in the input data.""" | ||
| status_code = 400 | ||
| def __init__(self, field_names: list): | ||
| self.field_names = field_names | ||
| self.message = "Missing required fields" | ||
| super().__init__(self.message) | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| class NotFoundError(Exception): | ||
| status_code = 404 | ||
| def __init__(self, resource="Resource", resource_id=None): | ||
| self.resource = resource | ||
| self.resource_id = resource_id | ||
| super().__init__() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
|
|
||
| from flask import jsonify, current_app | ||
| from sqlite3 import DatabaseError, OperationalError | ||
| from functools import wraps | ||
|
|
||
|
|
||
| def create_error_response(dev_message, prod_message=None, details=None): | ||
| """Create an error response based on the current environment.""" | ||
| mode = current_app.config.get('ENV', 'development') # Default to development if not set | ||
| response = {"error": dev_message} | ||
| if mode == 'development' and details: | ||
| response["details"] = details | ||
| if mode == 'production' and prod_message: | ||
| response["error"] = prod_message | ||
| return response | ||
|
|
||
|
|
||
| def handle_db_errors(f): | ||
| """Decorator to handle database errors and return JSON responses.""" | ||
| @wraps(f) | ||
| def wrapper(*args, **kwargs): | ||
| response = {} | ||
| try: | ||
| return f(*args, **kwargs) | ||
| except OperationalError as e: | ||
| response = create_error_response("Database Operational Error", "Database Operation could not be performed. Try Again Later!", details=str(e)) | ||
| return jsonify(response), 500 | ||
| except DatabaseError as e: | ||
| response = create_error_response("Database Error", details=str(e)) | ||
| return jsonify(response), 500 | ||
| return wrapper | ||
|
|
||
|
|
||
| def handle_missing_field_error(e): | ||
| """Handle MissingFieldError exceptions.""" | ||
| mode = current_app.config.get('ENV', 'development') # Default to development if not set | ||
| if( mode == 'development'): | ||
| response = {"error": e.message, "missing_fields": e.field_names} | ||
| else: | ||
| response = {"error": e.message} | ||
| return jsonify(response), e.status_code | ||
|
|
||
| def handle_not_found_error(e): | ||
| """Handle NotFoundError exceptions.""" | ||
| mode = current_app.config.get('ENV', 'development') # Default to development if not set | ||
| if mode == 'development' and e.resource_id is not None: | ||
| response = {"error": f"{e.resource} with ID {e.resource_id} not found"} | ||
| else: | ||
| response = {"error": f"{e.resource} not found"} | ||
| return jsonify(response), e.status_code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,119 +1,79 @@ | ||
| import sqlite3 | ||
| from flask import Blueprint, jsonify, request | ||
| from db.db import open_db, close_db | ||
| from db.db import open_db | ||
| from error_handling.handlers import handle_db_errors | ||
| from error_handling.error_classes import MissingFieldError, NotFoundError | ||
|
|
||
| appointments_bp = Blueprint('appointments', __name__) | ||
|
|
||
| @appointments_bp.route('/get_appointments', methods=['GET']) | ||
| @handle_db_errors | ||
| def get_appointments(): | ||
| db = open_db() | ||
|
|
||
| try: | ||
| appointments = db.execute('SELECT * FROM appointments').fetchall() | ||
| appointments_list = [dict(appt) for appt in appointments] | ||
| appointments = db.execute('SELECT * FROM appointments').fetchall() | ||
| appointments_list = [dict(appt) for appt in appointments] | ||
|
|
||
| return jsonify(appointments_list), 200 | ||
|
|
||
| except sqlite3.OperationalError: | ||
| return jsonify({"error": "Database Error"}), 500 | ||
| finally: | ||
| close_db(db) | ||
| return jsonify(appointments_list), 200 | ||
|
|
||
|
|
||
| @appointments_bp.route('/get_appointment/<int:appointment_id>', methods=['GET']) | ||
| @handle_db_errors | ||
| def get_appointment(appointment_id): | ||
| db = open_db() | ||
|
|
||
| if not appointment_id: | ||
| return jsonify({"error": "Appointment ID is required"}), 400 | ||
|
|
||
| try: | ||
| appointment = db.execute('SELECT * FROM appointments WHERE id = ?', (appointment_id,)).fetchone() | ||
| if not appointment: | ||
| return jsonify({"error": "Appointment not found"}), 404 | ||
| appointment = db.execute('SELECT * FROM appointments WHERE id = ?', (appointment_id,)).fetchone() | ||
| if not appointment: | ||
| raise NotFoundError(resource="Appointment entry", resource_id=appointment_id) | ||
|
|
||
| return jsonify(dict(appointment)), 200 | ||
| return jsonify(dict(appointment)), 200 | ||
|
|
||
| except sqlite3.OperationalError: | ||
| return jsonify({"error": "Database Error"}), 500 | ||
| finally: | ||
| close_db(db) | ||
|
|
||
| @appointments_bp.route('/add_appointment', methods=['POST']) | ||
| @handle_db_errors | ||
| def add_appointment(): | ||
| db = open_db() | ||
| try: | ||
| data = request.json | ||
| title = data.get('title') | ||
| content = data.get('content') | ||
| appointment_date = data.get('appointment_date') | ||
| appointment_time = data.get('appointment_time') | ||
| appointment_location = data.get('appointment_location') | ||
|
|
||
| if not all([title, content, appointment_date, appointment_time, appointment_location]): | ||
| return jsonify({"error": "Missing required fields"}), 400 | ||
|
|
||
| db.execute( | ||
| 'INSERT INTO appointments (title, content, appointment_date, appointment_time, appointment_location, appointment_status) VALUES (?, ?, ?, ?, ?, ?)', | ||
| (title, content, appointment_date, appointment_time, appointment_location, 'pending') | ||
| ) | ||
| db.commit() | ||
|
|
||
| return jsonify({"status": "success", "message": "Appointment added successfully"}), 200 | ||
| data = request.get_json() | ||
| required = ['title', 'content', 'appointment_date', 'appointment_time', 'appointment_location'] | ||
| missing = [field for field in required if field not in data] | ||
| if missing: | ||
| raise MissingFieldError(missing) | ||
|
|
||
| db.execute( | ||
| 'INSERT INTO appointments (title, content, appointment_date, appointment_time, appointment_location, appointment_status) VALUES (?, ?, ?, ?, ?, ?)', | ||
| (data["title"], data["content"], data["appointment_date"], data["appointment_time"], data["appointment_location"], 'pending') | ||
| ) | ||
| db.commit() | ||
| return jsonify({"status": "success", "message": "Appointment added successfully"}), 201 | ||
|
|
||
| except sqlite3.OperationalError: | ||
| return jsonify({"error": "Database Error"}), 500 | ||
| finally: | ||
| close_db(db) | ||
|
|
||
| @appointments_bp.route('/update_appointment/<int:appointment_id>', methods=['PUT']) | ||
| @appointments_bp.route('/update_appointment/<int:appointment_id>', methods=['PATCH']) | ||
| @handle_db_errors | ||
| def update_appointment(appointment_id): | ||
| db = open_db() | ||
|
|
||
| existing_appointment = db.execute('SELECT * FROM appointments WHERE id = ?', (appointment_id,)).fetchone() | ||
| if not existing_appointment: | ||
| return jsonify({"error": "Appointment not found"}), 404 | ||
|
|
||
| try: | ||
| data = request.json | ||
| title = data.get('title') | ||
| content = data.get('content') | ||
| appointment_date = data.get('appointment_date') | ||
| appointment_time = data.get('appointment_time') | ||
| appointment_location = data.get('appointment_location') | ||
| appointment_status = data.get('appointment_status', 'pending') | ||
|
|
||
| if not all([title, content, appointment_date, appointment_time, appointment_location]): | ||
| return jsonify({"error": "Missing required fields"}), 400 | ||
|
|
||
| db.execute( | ||
| 'UPDATE appointments SET title = ?, content = ?, appointment_date = ?, appointment_time = ?, appointment_location = ?, appointment_status = ? WHERE id = ?', | ||
| (title, content, appointment_date, appointment_time, appointment_location, appointment_status, appointment_id) | ||
| ) | ||
| db.commit() | ||
|
|
||
| return jsonify({"status": "success", "message": "Appointment updated successfully"}), 200 | ||
| raise NotFoundError(resource="Appointment entry", resource_id=appointment_id) | ||
| data = request.get_json() | ||
| title = data.get("title", existing_appointment["title"]) | ||
| content = data.get("content", existing_appointment["content"]) | ||
| appointment_date = data.get("appointment_date", existing_appointment["appointment_date"]) | ||
| appointment_time = data.get("appointment_time", existing_appointment["appointment_time"]) | ||
| appointment_location = data.get("appointment_location", existing_appointment["appointment_location"]) | ||
| appointment_status = data.get("appointment_status", existing_appointment["appointment_status"]) | ||
|
|
||
| db.execute( | ||
| 'UPDATE appointments SET title = ?, content = ?, appointment_date = ?, appointment_time = ?, appointment_location = ?, appointment_status = ? WHERE id = ?', | ||
| (title, content, appointment_date, appointment_time, appointment_location, appointment_status, appointment_id) | ||
| ) | ||
| db.commit() | ||
| return jsonify({"status": "success", "message": "Appointment updated successfully"}), 200 | ||
|
|
||
| except sqlite3.OperationalError: | ||
| return jsonify({"error": "Database Error"}), 500 | ||
| finally: | ||
| close_db(db) | ||
|
|
||
| @appointments_bp.route('/delete_appointment/<int:appointment_id>', methods=['DELETE']) | ||
| @handle_db_errors | ||
| def delete_appointment(appointment_id): | ||
| db = open_db() | ||
|
|
||
| existing_appointment = db.execute('SELECT * FROM appointments WHERE id = ?', (appointment_id,)).fetchone() | ||
| if not existing_appointment: | ||
| return jsonify({"error": "Appointment not found"}), 404 | ||
|
|
||
| try: | ||
| db.execute('DELETE FROM appointments WHERE id = ?', (appointment_id,)) | ||
| db.commit() | ||
|
|
||
| return jsonify({"status": "success", "message": "Appointment deleted successfully"}), 200 | ||
|
|
||
| except sqlite3.OperationalError: | ||
| return jsonify({"error": "Database Error"}), 500 | ||
| finally: | ||
| close_db(db) | ||
| result = db.execute('DELETE FROM appointments WHERE id = ?', (appointment_id,)) | ||
| if result.rowcount == 0: | ||
| raise NotFoundError(resource="Appointment entry", resource_id=appointment_id) | ||
| db.commit() | ||
| return jsonify({"status": "success", "message": "Appointment deleted successfully"}), 200 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.