zousko-stark commited on
Commit
f05c6ec
·
verified ·
1 Parent(s): d1c309d

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. main.py +29 -0
main.py CHANGED
@@ -1248,6 +1248,35 @@ app.add_middleware(
1248
  allow_headers=["*"],
1249
  )
1250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1251
  @app.middleware("http")
1252
  async def limit_concurrency(request: Request, call_next):
1253
  """Limit concurrent requests to MAX_CONCURRENT_USERS."""
 
1248
  allow_headers=["*"],
1249
  )
1250
 
1251
+ from fastapi.exceptions import RequestValidationError
1252
+ from fastapi.responses import JSONResponse
1253
+ from fastapi.encoders import jsonable_encoder
1254
+
1255
+ @app.exception_handler(RequestValidationError)
1256
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
1257
+ """
1258
+ Handle validation errors gracefully, stripping binary/unsafe data from logs/response.
1259
+ Fixes UnicodeDecodeError when multipart/form-data is sent to JSON endpoint.
1260
+ """
1261
+ errors = exc.errors()
1262
+ clean_errors = []
1263
+ for error in errors:
1264
+ copy = error.copy()
1265
+ # Remove raw binary input which causes jsonable_encoder crash
1266
+ if 'input' in copy:
1267
+ val = copy['input']
1268
+ if isinstance(val, (bytes, bytearray)):
1269
+ copy['input'] = "<binary_data_stripped>"
1270
+ elif isinstance(val, str) and len(val) > 200:
1271
+ copy['input'] = val[:200] + "..." # Truncate long inputs
1272
+ clean_errors.append(copy)
1273
+
1274
+ logger.warning(f"Validation Error on {request.url.path}: {clean_errors}")
1275
+ return JSONResponse(
1276
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
1277
+ content={"detail": jsonable_encoder(clean_errors)},
1278
+ )
1279
+
1280
  @app.middleware("http")
1281
  async def limit_concurrency(request: Request, call_next):
1282
  """Limit concurrent requests to MAX_CONCURRENT_USERS."""