Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Exceptions -HTTPException andWebSocketException

These are the exceptions that you can raise to show errors to the client.

When you raise an exception, as would happen with normal Python, the rest of the execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client.

You can use:

  • HTTPException
  • WebSocketException

These exceptions can be imported directly fromfastapi:

fromfastapiimportHTTPException,WebSocketException

fastapi.HTTPException

HTTPException(status_code,detail=None,headers=None)

Bases:HTTPException

An HTTP exception you can raise in your own code to show errors to the client.

This is for client errors, invalid authentication, invalid data, etc. Not for servererrors in your code.

Read more about it in theFastAPI docs for Handling Errors.

Example

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]}
PARAMETERDESCRIPTION
status_code

HTTP status code to send to the client.

Read more about it in theFastAPI docs for Handling Errors

TYPE:int

detail

Any data to be sent to the client in thedetail key of the JSONresponse.

Read more about it in theFastAPI docs for Handling Errors

TYPE:AnyDEFAULT:None

headers

Any headers to send to the client in the response.

Read more about it in theFastAPI docs for Handling Errors

TYPE:Mapping[str,str] | NoneDEFAULT:None

Source code infastapi/exceptions.py
454647484950515253545556575859606162636465666768697071727374757677787980818283
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)

status_codeinstance-attribute

status_code=status_code

detailinstance-attribute

detail=detail

headersinstance-attribute

headers=headers

fastapi.WebSocketException

WebSocketException(code,reason=None)

Bases:WebSocketException

A WebSocket exception you can raise in your own code to show errors to the client.

This is for client errors, invalid authentication, invalid data, etc. Not for servererrors in your code.

Read more about it in theFastAPI docs for WebSockets.

Example

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}")
PARAMETERDESCRIPTION
code

TYPE:int

reason

The reason to close the WebSocket connection.

It is UTF-8-encoded data. The interpretation of the reason is up to theapplication, it is not specified by the WebSocket specification.

It could contain text that could be human-readable or interpretableby the client code, etc.

TYPE:str | NoneDEFAULT:None

Source code infastapi/exceptions.py
128129130131132133134135136137138139140141142143144145146147148149150151152153154
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)

codeinstance-attribute

code=code

reasoninstance-attribute

reason=reasonor''

[8]ページ先頭

©2009-2026 Movatter.jp