Skip to content

Commit 22d88cd

Browse files
committed
http and validation error handlers
1 parent 000f017 commit 22d88cd

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

vetiver/server.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@
55
import pandas as pd
66
import requests
77
import uvicorn
8-
from fastapi import FastAPI, Request, testclient
8+
from fastapi import FastAPI, Request, testclient, status
9+
from fastapi.encoders import jsonable_encoder
10+
from fastapi.exceptions import RequestValidationError
911
from fastapi.openapi.utils import get_openapi
10-
from fastapi.responses import HTMLResponse, RedirectResponse
12+
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
13+
from fastapi.responses import PlainTextResponse
14+
from starlette.exceptions import HTTPException as StarletteHTTPException
1115
from warnings import warn
1216

1317
from .utils import _jupyter_nb
@@ -138,6 +142,19 @@ async def rapidoc():
138142
</html>
139143
"""
140144

145+
@app.exception_handler(RequestValidationError)
146+
async def validation_exception_handler(
147+
request: Request, exc: RequestValidationError
148+
):
149+
return JSONResponse(
150+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
151+
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
152+
)
153+
154+
@app.exception_handler(StarletteHTTPException)
155+
async def http_exception_handler(request, exc):
156+
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
157+
141158
return app
142159

143160
def vetiver_post(self, endpoint_fx: Callable, endpoint_name: str = None, **kw):
@@ -266,7 +283,7 @@ def predict(endpoint, data: Union[dict, pd.DataFrame, pd.Series], **kw) -> pd.Da
266283
except (requests.exceptions.HTTPError, httpx.HTTPStatusError) as e:
267284
if response.status_code == 422:
268285
raise TypeError(
269-
f"Predict expects DataFrame, Series, or dict. Given type is {type(data)}"
286+
PlainTextResponse(str(response), status_code=response.status_code)
270287
)
271288
raise requests.exceptions.HTTPError(
272289
f"Could not obtain data from endpoint with error: {e}"

0 commit comments

Comments
 (0)