Skip to content

Commit

Permalink
add global value error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
sierra-moxon committed Aug 12, 2024
1 parent 6a947d3 commit 99e3f83
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
19 changes: 17 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""main application entry point."""

import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

from fastapi.responses import JSONResponse
import requests
from app.middleware.logging_middleware import LoggingMiddleware
from app.routers import (
bioentity,
Expand All @@ -18,6 +19,9 @@
slimmer,
users_and_groups,
)
import logging

logger = logging.getLogger("uvicorn.error")

app = FastAPI(
title="GO API",
Expand Down Expand Up @@ -54,13 +58,24 @@
)


# Global exception handler for ValueErrors
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
logger.error(f"Value error occurred: {exc}")
return JSONResponse(
status_code=400,
content={"message": f"Value error occurred: {exc}"}
)


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"message": "An unexpected error occurred. Please try again later."},
)


@app.exception_handler(requests.exceptions.RequestException)
async def requests_exception_handler(request: Request, exc: requests.exceptions.RequestException):
return JSONResponse(
Expand Down
3 changes: 3 additions & 0 deletions app/routers/pathway_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ async def get_gocams_by_geneproduct_id(
(e.g. MGI:3588192, ZFIN:ZDB-GENE-000403-1).
"""
if ":" not in id:
raise ValueError("Invalid CURIE format")

if id.startswith("MGI:MGI:"):
id = id.replace("MGI:MGI:", "MGI:")

Expand Down
24 changes: 24 additions & 0 deletions tests/unit/test_global_exception_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from fastapi.testclient import TestClient
from app.main import app

test_client = TestClient(app)


def test_value_error_handler():
# Simulate an endpoint that raises a ValueError (e.g., by sending an invalid CURIE)
response = test_client.get("/api/ontol/labeler?id=@base:invalid")

# Verify that the global exception handler for ValueErrors, rewrites as an internal server error code.
assert response.status_code == 400
response = test_client.get(f"/api/gp/P05067/models")


def test_value_error_curie():
response = test_client.get(f"/api/gp/P05067/models")
assert response.status_code == 400
assert response.json() == {"message": "Value error occurred: Invalid CURIE format"}


def test_ncbi_taxon_error_handling():
response = test_client.get("/api/taxon/NCBITaxon%3A4896/models")
assert response.status_code == 200

0 comments on commit 99e3f83

Please sign in to comment.