Skip to content

Commit

Permalink
Returns "message" as an object instead of a string, when a BadRequest
Browse files Browse the repository at this point in the history
occurs

This makes it possible for the error message to reach the client as an
object, avoiding the need for string-to-object conversions.
  • Loading branch information
wesleybl committed Feb 21, 2024
1 parent 44089ed commit d37910b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/plone/rest/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from Products.Five.browser import BrowserView
from urllib.parse import quote
from urllib.parse import unquote
from zExceptions import BadRequest
from zExceptions import NotFound
from zope.component import adapter
from zope.component import queryMultiAdapter
Expand Down Expand Up @@ -57,7 +58,10 @@ def __call__(self):

def render_exception(self, exception):
name = type(exception).__name__
message = str(exception)
if isinstance(exception, BadRequest):
message = exception.args[0]
else:
message = str(exception)
result = {"type": name, "message": message}

policy = queryMultiAdapter((self.context, self.request), ICORSPolicy)
Expand Down
9 changes: 9 additions & 0 deletions src/plone/rest/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,12 @@ def __call__(self):
{},
None,
)


class BadRequestService(Service):
def __call__(self):
from zExceptions import BadRequest

errors = [{"error": "ValidationError", "message": "message error"}]

raise BadRequest(errors)
8 changes: 8 additions & 0 deletions src/plone/rest/testing.zcml
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,12 @@
expose_headers="X-My-Header"
/>

<plone:service
method="GET"
factory=".testing.BadRequestService"
for="*"
permission="zope2.View"
name="bad-request-error"
/>

</configure>
11 changes: 11 additions & 0 deletions src/plone/rest/tests/test_error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,14 @@ def test_500_traceback_only_for_manager_users(self):
self.assertRegex(
traceback[0], r'^File "[^"]*", line \d*, in (publish|transaction_pubevents)'
)

def test_bad_request_error_message(self):
response = requests.get(
f"{self.portal_url}/bad-request-error",
headers={"Accept": "application/json"},
auth=(SITE_OWNER_NAME, SITE_OWNER_PASSWORD),
)
self.assertEquals(
response.json()["message"],
[{"error": "ValidationError", "message": "message error"}],
)

0 comments on commit d37910b

Please sign in to comment.