Skip to content

Commit

Permalink
move the error handling logic to write_error for the /curl handler
Browse files Browse the repository at this point in the history
  • Loading branch information
shtlrs committed Jan 20, 2024
1 parent 002b21f commit 7008f97
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions src/pinnwand/handler/api_curl.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import Any
from urllib.parse import urljoin

import tornado.web

from pinnwand import configuration, database, defensive, logger, utility
from pinnwand import configuration, database, defensive, error, logger, utility

log = logger.get_logger(__name__)

Expand All @@ -14,11 +15,21 @@ def check_xsrf_cookie(self) -> None:
def get(self) -> None:
raise tornado.web.HTTPError(400)

def post(self) -> None:
if defensive.ratelimit(self.request, area="create"):
def write_error(self, status_code: int, **kwargs: Any) -> None:
type_, exc, traceback = kwargs["exc_info"]

if type_ == error.ValidationError:
self.set_status(400)
self.write(str(exc))
elif type_ == error.RatelimitError:
self.set_status(429)
self.write("Enhance your calm, you have exceeded the ratelimit.")
return
else:
super().write_error(status_code, **kwargs)

def post(self) -> None:
if defensive.ratelimit(self.request, area="create"):
raise error.RatelimitError

lexer = self.get_body_argument("lexer", "text")
raw = self.get_body_argument("raw", "", strip=False)
Expand All @@ -30,22 +41,16 @@ def post(self) -> None:
log.info(
"CurlCreate.post: a paste was submitted with an invalid lexer"
)
self.set_status(400)
self.write("Invalid `lexer` supplied.\n")
return
raise error.ValidationError("Invalid `lexer` supplied.\n")

# Guard against empty strings
if not raw or not raw.strip():
log.info("CurlCreate.post: a paste was submitted without raw")
self.set_status(400)
self.write("Invalid `raw` supplied.\n")
return
raise error.ValidationError("Invalid `raw` supplied.\n")

if expiry not in configuration.expiries:
log.info("CurlCreate.post: a paste was submitted without raw")
self.set_status(400)
self.write("Invalid `expiry` supplied.\n")
return
raise error.ValidationError("Invalid `expiry` supplied.\n")

paste = database.Paste(
utility.slug_create(), configuration.expiries[expiry], "curl"
Expand Down

0 comments on commit 7008f97

Please sign in to comment.