Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom exception to handle missing boundary error #1544

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions starlette/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
from starlette.types import ASGIApp, Message, Receive, Scope, Send


class MissingBoundaryException(Exception):
def __init__(self):
super().__init__("Form data is missing boundary parameter")


class HTTPException(Exception):
def __init__(
self, status_code: int, detail: str = None, headers: dict = None
Expand Down
7 changes: 6 additions & 1 deletion starlette/formparsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,17 @@ def on_end(self) -> None:
self.messages.append(message)

async def parse(self) -> FormData:
from starlette.exceptions import MissingBoundaryException
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid a circular import error, I've added an import line in the function instead of top-level in the module


# Parse the Content-Type header to get the multipart boundary.
content_type, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if type(charset) == bytes:
charset = charset.decode("latin-1")
boundary = params[b"boundary"]
try:
boundary = params[b"boundary"]
except KeyError:
raise MissingBoundaryException

# Callbacks dictionary.
callbacks = {
Expand Down
3 changes: 2 additions & 1 deletion tests/test_formparsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import pytest

from starlette.exceptions import MissingBoundaryException
from starlette.formparsers import UploadFile, _user_safe_decode
from starlette.requests import Request
from starlette.responses import JSONResponse
Expand Down Expand Up @@ -392,7 +393,7 @@ def test_user_safe_decode_ignores_wrong_charset():

def test_missing_boundary_parameter(test_client_factory):
client = test_client_factory(app)
with pytest.raises(KeyError, match="boundary"):
with pytest.raises(MissingBoundaryException):
client.post(
"/",
data=(
Expand Down