falconry / falcon

The no-magic web data plane API and microservices framework for Python developers, with a focus on reliability, correctness, and performance at scale.
https://falcon.readthedocs.io/en/stable/
Apache License 2.0
9.51k stars 937 forks source link

feat(errors): default error serializer content negotiation #2190

Closed copalco closed 1 day ago

copalco commented 10 months ago

Summary of Changes

We would like to use choose from available content type handlers to return error response content in a best format basing on the accept header of the request.

Related Issues

Fixes https://github.com/falconry/falcon/issues/2023 Fixes #2349

Pull Request Checklist

This is just a reminder about the most common mistakes. Please make sure that you tick all appropriate boxes. But please read our contribution guide at least once; it will save you a few review cycles!

If an item doesn't apply to your pull request, check it anyway to make it apparent that there's nothing to do.

If you have any questions to any of the points above, just submit and ask! This checklist is here to help you, not to deter you from contributing!

PR template inspired by the attrs project.

codecov[bot] commented 10 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 100.00%. Comparing base (a0da915) to head (3506dea). Report is 1 commits behind head on master.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #2190 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 64 64 Lines 7621 7624 +3 Branches 1244 1246 +2 ========================================= + Hits 7621 7624 +3 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

CaselIT commented 2 days ago

@copalco I've taken the liberty of improving the implementation.

@vytas7 should be ready for review. It should be mostly backward compatible, but I feel it's still better to have this for 4.0 instead of 4.x

vytas7 commented 2 days ago

This is a simple test app that I used:

import falcon.asgi
import falcon.media

class AsyncHandler(falcon.media.BaseHandler):
    async def serialize_async(self, media, content_type):
        return f'{media}\n'.encode()

class Resource:
    async def on_get(self, req, resp):
        if not req.get_param('password'):
            raise falcon.HTTPForbidden(title='NotAllowed')

        resp.content_type = 'falcon/peregrine'
        resp.media = {'msg': 'Hello'}

app = falcon.asgi.App()
app.resp_options.media_handlers['falcon/peregrine'] = AsyncHandler()
app.add_route('/', Resource())

Rendering normal media using my new handler works:

$ xh http://localhost:8000/?password=secret Accept:falcon/peregrine

HTTP/1.1 200 OK
Content-Length: 17
Content-Type: falcon/peregrine
Date: Sun, 29 Sep 2024 10:44:42 GMT
Server: uvicorn

{'msg': 'Hello'}

Going via the exception route fails with an internal server error:

$ xh http://localhost:8000/ Accept:falcon/peregrine

HTTP/1.1 500 Internal Server Error
Connection: close
Content-Length: 21
Content-Type: text/plain; charset=utf-8
Date: Sun, 29 Sep 2024 10:45:39 GMT
Server: uvicorn

Internal Server Error
Traceback (most recent call last):
  File "/home/vytas/.virtualenvs/falcon-py312/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 401, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vytas/.virtualenvs/falcon-py312/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 70, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/asgi/app.py", line 529, in __call__
    if not await self._handle_exception(req, resp, ex, params):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/asgi/app.py", line 1299, in _handle_exception
    await err_handler(req, resp, ex, params, **kwargs)
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/asgi/app.py", line 1207, in _http_error_handler
    self._compose_error_response(req, resp, error)
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/app.py", line 1126, in _compose_error_response
    self._serialize_error(req, resp, error)
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/app_helpers.py", line 328, in default_serialize_error
    resp.data = handler.serialize(exception.to_dict(), preferred)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vytas/progs/tmp/copalco/falcon/falcon/media/base.py", line 61, in serialize
    raise NotImplementedError()
NotImplementedError
CaselIT commented 2 days ago

good catch! fixed it

CaselIT commented 2 days ago

@vytas7 updated

CaselIT commented 1 day ago

Updated.

We also need to make a decision on being able to disable XML, and whether to make a breaking change, and disable XML by default.

Not too sure about this. Let's merge this one and think about it after

vytas7 commented 1 day ago

As discussed on Gitter, we don't want to make a breaking change wrt XML right now.