From 84f27d0ab83dba21926ed79138317e5b1ff56a70 Mon Sep 17 00:00:00 2001 From: shtlrs Date: Sun, 10 Mar 2024 22:17:08 +0100 Subject: [PATCH] move the error handling logic to `write_error` for the /curl handler --- src/pinnwand/handler/api_curl.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/pinnwand/handler/api_curl.py b/src/pinnwand/handler/api_curl.py index afb57dd..0de25ed 100644 --- a/src/pinnwand/handler/api_curl.py +++ b/src/pinnwand/handler/api_curl.py @@ -1,10 +1,11 @@ +from typing import Any from urllib.parse import urljoin import tornado.web -from pinnwand import defensive, logger, utility from pinnwand.configuration import Configuration, ConfigurationProvider from pinnwand.database import models, manager +from pinnwand import defensive, error, logger, utility log = logger.get_logger(__name__) @@ -16,11 +17,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 configuration: Configuration = ConfigurationProvider.get_config() lexer = self.get_body_argument("lexer", "text") @@ -33,22 +44,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 = models.Paste( utility.slug_create(), configuration.expiries[expiry], "curl"