vinith17 commited on
Commit
1fc2334
·
1 Parent(s): 822c184

fix: correct FastAPI error handling and endpoint responses

Browse files

- Fix HTTPException usage for proper error responses
- Improve frontend error handling and logging
- Ensure /api/review endpoint returns valid JSON
- Remove test file from tracking

Files changed (2) hide show
  1. main.py +23 -15
  2. templates/index.html +9 -3
main.py CHANGED
@@ -1,8 +1,8 @@
1
  from openenv.core.env_server import create_fastapi_app
2
  from environment import CodeBugEnvironment
3
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
- from fastapi.responses import HTMLResponse
5
- from fastapi import Request
6
  from pydantic import BaseModel
7
  import os
8
  import json
@@ -31,19 +31,27 @@ class ReviewRequest(BaseModel):
31
  @app.post("/api/review")
32
  async def review_code(request: ReviewRequest):
33
  """Analyze code and return bug findings"""
34
- code = request.code.strip()
35
- lang = request.language.lower()
36
-
37
- if not code:
38
- return {"error": "Code cannot be empty"}, 400
39
- if not lang:
40
- return {"error": "Language must be specified"}, 400
41
- if len(code) > 5000:
42
- return {"error": "Code exceeds 5000 characters"}, 400
43
-
44
- # Local pattern-based analysis (since this is a demo)
45
- result = analyze_code_locally(code, lang)
46
- return result
 
 
 
 
 
 
 
 
47
 
48
  def analyze_code_locally(code: str, lang: str) -> dict:
49
  """Pattern-based code analysis - production would use LLM"""
 
1
  from openenv.core.env_server import create_fastapi_app
2
  from environment import CodeBugEnvironment
3
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
+ from fastapi.responses import HTMLResponse, JSONResponse
5
+ from fastapi import Request, HTTPException
6
  from pydantic import BaseModel
7
  import os
8
  import json
 
31
  @app.post("/api/review")
32
  async def review_code(request: ReviewRequest):
33
  """Analyze code and return bug findings"""
34
+ try:
35
+ code = request.code.strip()
36
+ lang = request.language.lower()
37
+
38
+ if not code:
39
+ raise HTTPException(status_code=400, detail="Code cannot be empty")
40
+ if not lang:
41
+ raise HTTPException(status_code=400, detail="Language must be specified")
42
+ if len(code) > 5000:
43
+ raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
44
+
45
+ # Local pattern-based analysis
46
+ result = analyze_code_locally(code, lang)
47
+ return result
48
+ except HTTPException:
49
+ raise
50
+ except Exception as e:
51
+ return JSONResponse(
52
+ status_code=500,
53
+ content={"error": str(e)}
54
+ )
55
 
56
  def analyze_code_locally(code: str, lang: str) -> dict:
57
  """Pattern-based code analysis - production would use LLM"""
templates/index.html CHANGED
@@ -787,16 +787,22 @@ async function doReview() {
787
  document.getElementById('rLoading').classList.add('on');
788
 
789
  try {
790
- const res = await fetch('/api/review', {
791
  method: 'POST',
792
  headers: { 'Content-Type': 'application/json' },
793
  body: JSON.stringify({ code, language: lang })
794
  });
 
 
 
 
 
 
795
  const data = await res.json();
796
- if (!res.ok) throw new Error(data.error || 'API error');
797
  renderResult(data);
798
  } catch (err) {
799
- console.warn('Backend unavailable, using local analysis:', err.message);
 
800
  renderResult(mockReview(code, lang));
801
  } finally {
802
  btn.disabled = false;
 
787
  document.getElementById('rLoading').classList.add('on');
788
 
789
  try {
790
+ const res = await fetch('/api/review', {
791
  method: 'POST',
792
  headers: { 'Content-Type': 'application/json' },
793
  body: JSON.stringify({ code, language: lang })
794
  });
795
+
796
+ if (!res.ok) {
797
+ const errData = await res.json().catch(() => ({}));
798
+ throw new Error(errData.detail || errData.error || `API error: ${res.status}`);
799
+ }
800
+
801
  const data = await res.json();
 
802
  renderResult(data);
803
  } catch (err) {
804
+ console.error('API call failed:', err.message);
805
+ console.warn('Falling back to local analysis...');
806
  renderResult(mockReview(code, lang));
807
  } finally {
808
  btn.disabled = false;