Skip to content
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

refactor(backend): better error handling in backend #277

Merged
merged 7 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions backend/editor/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def check_single(id):
if len(id) == 0:
raise HTTPException(status_code=404, detail="Entry not found")
elif len(id) > 1:
raise HTTPException(status_code=500, detail="Multiple entries found")
raise HTTPException(status_code=409, detail="Multiple entries found")
Piv94165 marked this conversation as resolved.
Show resolved Hide resolved


def file_cleanup(filepath):
Expand All @@ -111,7 +111,7 @@ def file_cleanup(filepath):
try:
os.remove(filepath)
except Exception as e:
raise HTTPException(status_code=500, detail="Taxonomy file not found for deletion") from e
raise HTTPException(status_code=404, detail="Taxonomy file not found for deletion") from e
Piv94165 marked this conversation as resolved.
Show resolved Hide resolved


class StatusFilter(str, Enum):
Expand Down Expand Up @@ -139,6 +139,16 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
)


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""
Custom exception handler to log FastAPI exceptions.
"""
# Log the detail message
log.info(f" ERROR: {exc.detail}")
return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
alexgarel marked this conversation as resolved.
Show resolved Hide resolved


# Get methods


Expand Down Expand Up @@ -351,10 +361,10 @@ async def export_to_github(
return url

except GithubBranchExistsError:
raise HTTPException(status_code=500, detail="The Github branch already exists!")
raise HTTPException(status_code=409, detail="The Github branch already exists!")

except GithubUploadError:
raise HTTPException(status_code=500, detail="Github upload error!")
raise HTTPException(status_code=400, detail="Github upload error!")


# Post methods
Expand All @@ -370,7 +380,7 @@ async def import_from_github(request: Request, branch: str, taxonomy_name: str):

taxonomy = TaxonomyGraph(branch, taxonomy_name)
if not taxonomy.is_valid_branch_name():
raise HTTPException(status_code=400, detail="branch_name: Enter a valid branch name!")
raise HTTPException(status_code=422, detail="branch_name: Enter a valid branch name!")
if await taxonomy.does_project_exist():
raise HTTPException(status_code=409, detail="Project already exists!")
if not await taxonomy.is_branch_unique():
Expand All @@ -390,7 +400,7 @@ async def upload_taxonomy(
# use the file name as the taxonomy name
taxonomy = TaxonomyGraph(branch, taxonomy_name)
if not taxonomy.is_valid_branch_name():
raise HTTPException(status_code=400, detail="branch_name: Enter a valid branch name!")
raise HTTPException(status_code=422, detail="branch_name: Enter a valid branch name!")
if await taxonomy.does_project_exist():
raise HTTPException(status_code=409, detail="Project already exists!")
if not await taxonomy.is_branch_unique():
Expand Down
51 changes: 36 additions & 15 deletions backend/editor/github_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"""
from textwrap import dedent

from github import Github
from fastapi import HTTPException
from github import Github, GithubException

from . import settings

Expand All @@ -21,8 +22,19 @@ def init_driver_and_repo(self):
"""
Initalize connection to Github with an access token
"""
github_driver = Github(settings.access_token)
repo = github_driver.get_repo(settings.repo_uri)
access_token = settings.access_token
if not access_token:
raise HTTPException(
status_code=400,
detail="Access token is not set. Please add your access token in .env",
)
alexgarel marked this conversation as resolved.
Show resolved Hide resolved
repo_uri = settings.repo_uri
if not repo_uri:
raise HTTPException(
status_code=400, detail="repo_uri is not set. Please add your access token in .env"
)
github_driver = Github(access_token)
repo = github_driver.get_repo(repo_uri)
return repo

def list_all_branches(self):
Expand All @@ -47,19 +59,28 @@ def update_file(self, filename):
# Find taxonomy text file to be updated
github_filepath = f"taxonomies/{self.taxonomy_name}.txt"
commit_message = f"Update {self.taxonomy_name}.txt"
try:
current_file = self.repo.get_contents(github_filepath)
with open(filename, "r") as f:
new_file_contents = f.read()

current_file = self.repo.get_contents(github_filepath)
with open(filename, "r") as f:
new_file_contents = f.read()

# Update the file
self.repo.update_file(
github_filepath,
commit_message,
new_file_contents,
current_file.sha,
branch=self.branch_name,
)
# Update the file
self.repo.update_file(
github_filepath,
commit_message,
new_file_contents,
current_file.sha,
branch=self.branch_name,
)
except GithubException as e:
# Handle GitHub API-related exceptions
raise Exception(f"GitHub API error: {e}")
except FileNotFoundError:
# Handle file not found error (e.g., when 'filename' does not exist)
raise Exception(f"File not found: {filename}")
except Exception as e:
# Handle any other unexpected exceptions
raise Exception(f"An error occurred: {e}")
Piv94165 marked this conversation as resolved.
Show resolved Hide resolved

def create_pr(self, description):
"""
Expand Down