Estas son las excepciones que puedes lanzar para mostrar errores al cliente.
Cuando lanzas una excepción, como pasaría con Python normal, el resto de la ejecución se aborta. De esta manera puedes lanzar estas excepciones desde cualquier parte del código para abortar una petición y mostrar el error al cliente.
Puedes usar:
HTTPException
WebSocketException
Estas excepciones pueden ser importadas directamente desde fastapi:
fromfastapiimportFastAPI,HTTPExceptionapp=FastAPI()items={"foo":"The Foo Wrestlers"}@app.get("/items/{item_id}")asyncdefread_item(item_id:str):ifitem_idnotinitems:raiseHTTPException(status_code=404,detail="Item not found")return{"item":items[item_id]}
def__init__(self,status_code:Annotated[int,Doc(""" HTTP status code to send to the client. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) """),],detail:Annotated[Any,Doc(""" Any data to be sent to the client in the `detail` key of the JSON response. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) """),]=None,headers:Annotated[Mapping[str,str]|None,Doc(""" Any headers to send to the client in the response. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) """),]=None,)->None:super().__init__(status_code=status_code,detail=detail,headers=headers)
fromtypingimportAnnotatedfromfastapiimport(Cookie,FastAPI,WebSocket,WebSocketException,status,)app=FastAPI()@app.websocket("/items/{item_id}/ws")asyncdefwebsocket_endpoint(*,websocket:WebSocket,session:Annotated[str|None,Cookie()]=None,item_id:str,):ifsessionisNone:raiseWebSocketException(code=status.WS_1008_POLICY_VIOLATION)awaitwebsocket.accept()whileTrue:data=awaitwebsocket.receive_text()awaitwebsocket.send_text(f"Session cookie is: {session}")awaitwebsocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
Son datos codificados en UTF-8. La interpretación de la razón depende de la
aplicación, no está especificada por la especificación de WebSocket.
Podría contener texto que sea legible por humanos o interpretable
por el código del cliente, etc.
TYPE:str | NoneDEFAULT:None
Código fuente en fastapi/exceptions.py
def__init__(self,code:Annotated[int,Doc(""" A closing code from the [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). """),],reason:Annotated[str|None,Doc(""" The reason to close the WebSocket connection. It is UTF-8-encoded data. The interpretation of the reason is up to the application, it is not specified by the WebSocket specification. It could contain text that could be human-readable or interpretable by the client code, etc. """),]=None,)->None:super().__init__(code=code,reason=reason)