from tornado.testing import AsyncHTTPTestCase, ExpectLog
from tornado.test.util import unittest
from tornado.util import u, bytes_type, ObjectDict, unicode_type
-from tornado.web import RequestHandler, authenticated, Application, asynchronous, url, HTTPError, StaticFileHandler, _create_signature, create_signed_value, ErrorHandler, UIModule
+from tornado.web import RequestHandler, authenticated, Application, asynchronous, url, HTTPError, StaticFileHandler, _create_signature, create_signed_value, ErrorHandler, UIModule, MissingArgumentError
import binascii
import datetime
self.assertEqual(response.body,
b'In my_ui_method(42) with handler value asdf. '
b'In MyModule(123) with handler value asdf.')
+
+
+@wsgi_safe
+class GetArgumentErrorTest(SimpleHandlerTestCase):
+ class Handler(RequestHandler):
+ def get(self):
+ try:
+ self.get_argument('foo')
+ self.write({})
+ except MissingArgumentError as e:
+ self.write({'arg_name': e.arg_name,
+ 'log_message': e.log_message})
+
+ def test_catch_error(self):
+ response = self.fetch('/')
+ self.assertEqual(json_decode(response.body),
+ {'arg_name': 'foo',
+ 'log_message': 'Missing argument foo'})
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
- required, and we throw an HTTP 400 exception if it is missing.
+ required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
args = self.get_arguments(name, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
- raise HTTPError(400, "Missing argument %s" % name)
+ raise MissingArgumentError(name)
return default
return args[-1]
return message
+class MissingArgumentError(HTTPError):
+ """Exception raised by `RequestHandler.get_argument`.
+
+ This is a subclass of `HTTPError`, so if it is uncaught a 400 response
+ code will be used instead of 500 (and a stack trace will not be logged).
+ """
+ def __init__(self, arg_name):
+ super(MissingArgumentError, self).__init__(
+ 400, 'Missing argument %s' % arg_name)
+ self.arg_name = arg_name
+
+
class ErrorHandler(RequestHandler):
"""Generates an error response with ``status_code`` for all requests."""
def initialize(self, status_code):