An exception that will turn into an HTTP error response. Raising an `HTTPError` is a convenient alternative to calling `RequestHandler.send_error` since it automatically ends the current function. To customize the response sent with an `HTTPError`, override `RequestHandler.writ
| 2535 | |
| 2536 | |
| 2537 | class HTTPError(Exception): |
| 2538 | """An exception that will turn into an HTTP error response. |
| 2539 | |
| 2540 | Raising an `HTTPError` is a convenient alternative to calling |
| 2541 | `RequestHandler.send_error` since it automatically ends the |
| 2542 | current function. |
| 2543 | |
| 2544 | To customize the response sent with an `HTTPError`, override |
| 2545 | `RequestHandler.write_error`. |
| 2546 | |
| 2547 | :arg int status_code: HTTP status code. Must be listed in |
| 2548 | `httplib.responses <http.client.responses>` unless the ``reason`` |
| 2549 | keyword argument is given. |
| 2550 | :arg str log_message: Message to be written to the log for this error |
| 2551 | (will not be shown to the user unless the `Application` is in debug |
| 2552 | mode). May contain ``%s``-style placeholders, which will be filled |
| 2553 | in with remaining positional parameters. |
| 2554 | :arg str reason: Keyword-only argument. The HTTP "reason" phrase |
| 2555 | to pass in the status line along with ``status_code`` (for example, |
| 2556 | the "Not Found" in ``HTTP/1.1 404 Not Found``). Normally |
| 2557 | determined automatically from ``status_code``, but can be used |
| 2558 | to use a non-standard numeric code. This is not a general-purpose |
| 2559 | error message. |
| 2560 | """ |
| 2561 | |
| 2562 | def __init__( |
| 2563 | self, |
| 2564 | status_code: int = 500, |
| 2565 | log_message: Optional[str] = None, |
| 2566 | *args: Any, |
| 2567 | **kwargs: Any, |
| 2568 | ) -> None: |
| 2569 | self.status_code = status_code |
| 2570 | self._log_message = log_message |
| 2571 | self.args = args |
| 2572 | self.reason = kwargs.get("reason", None) |
| 2573 | |
| 2574 | @property |
| 2575 | def log_message(self) -> Optional[str]: |
| 2576 | """ |
| 2577 | A backwards compatible way of accessing log_message. |
| 2578 | """ |
| 2579 | if self._log_message and not self.args: |
| 2580 | return self._log_message.replace("%", "%%") |
| 2581 | return self._log_message |
| 2582 | |
| 2583 | def get_message(self) -> Optional[str]: |
| 2584 | if self._log_message and self.args: |
| 2585 | return self._log_message % self.args |
| 2586 | return self._log_message |
| 2587 | |
| 2588 | def __str__(self) -> str: |
| 2589 | message = "HTTP %d: %s" % ( |
| 2590 | self.status_code, |
| 2591 | self.reason or httputil.responses.get(self.status_code, "Unknown"), |
| 2592 | ) |
| 2593 | log_message = self.get_message() |
| 2594 | if log_message: |