def write_json(self, chunk, code=None, headers=None): """A convenient method that binds `chunk`, `code`, `headers` together chunk could be any type of (str, dict, list) """ assert chunk is not None, 'None cound not be written in write_json' self.set_header("Content-Type", "application/json; charset=UTF-8") if isinstance(chunk, dict) or isinstance(chunk, list): chunk = self.json_encode(chunk) # convert chunk to utf8 before `RequestHandler.write()` # so that if any error occurs, we can catch and log it try: chunk = utf8(chunk) except Exception: app_log.error('chunk encoding error, repr: %s' % repr(chunk)) raise_exc_info(sys.exc_info()) self.write(chunk) if code: self.set_status(code) if headers: for k, v in headers.items(): self.set_header(k, v)
def _exception_default_handler(self, e): """This method is a copy of tornado.web.RequestHandler._handle_request_exception """ if isinstance(e, HTTPError): if e.log_message: format = "%d %s: " + e.log_message args = [e.status_code, self._request_summary()] + list(e.args) app_log.warning(format, *args) if e.status_code not in httplib.responses: app_log.error("Bad HTTP status code: %d", e.status_code) self.send_error(500, exc_info=sys.exc_info()) else: self.send_error(e.status_code, exc_info=sys.exc_info()) else: app_log.error("Uncaught exception %s\n%r", self._request_summary(), self.request, exc_info=True) self.send_error(500, exc_info=sys.exc_info())