How to pass custom reason to 'write_error' through 'raise tornado.web.HTTPError(...)'?

465 views
Skip to first unread message

mrtn

unread,
Apr 29, 2015, 9:15:56 PM4/29/15
to python-...@googlegroups.com

I want to use 'raise tornado.web.HTTPError(400, reason='invalid request')' to pass a custom reason to the error response, and I hope to do this by overriding 'write_error (self, status_code, **kwargs)' method.

But it seems that I can only access 'self._reason' inside 'write_error', which is not what I want. I also tried `kwargs['reason'] but that does not exist.

Any suggestion?


Ben Darnell

unread,
Apr 29, 2015, 9:33:01 PM4/29/15
to Tornado Mailing List
The exception that exposed the error is available to write_error as an exc_info triple in the keyword arguments. You can access the reason field with something like this:
    if "exc_info" in kwargs:
      e = kwargs["exc_info"][1]
      if isinstance(e, tornado.web.HTTPError):
          reason = e.reason

But note that the "reason" field is essentially deprecated (it is not present in HTTP/2), so it's probably not the best way to do whatever you're trying to do here (HTTPError's log_message field is a little better, but still not ideal). Just raise your own exception instead of using HTTPError; your write_error override can use `self.set_status(400)` when it sees the right kind of exception.

-Ben

--
You received this message because you are subscribed to the Google Groups "Tornado Web Server" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-tornad...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

mrtn

unread,
Apr 29, 2015, 10:15:40 PM4/29/15
to python-...@googlegroups.com, b...@bendarnell.com

I see. So basically I check for my own custom exception inside 'write_error' by doing 'if isinstance(e, MyOwnException):', and set the status and use whatever message in the exception there.

Thanks for the suggestions!
Reply all
Reply to author
Forward
0 new messages