diff --git a/sanic/mixins/startup.py b/sanic/mixins/startup.py index 5e640fed4c..0d133f474d 100644 --- a/sanic/mixins/startup.py +++ b/sanic/mixins/startup.py @@ -49,7 +49,7 @@ from sanic.application.state import ApplicationServerInfo, Mode, ServerStage from sanic.base.meta import SanicMeta from sanic.compat import OS_IS_WINDOWS, StartMethod -from sanic.exceptions import ServerKilled +from sanic.exceptions import SanicException, ServerKilled from sanic.helpers import Default, _default, is_atty from sanic.http.constants import HTTP from sanic.http.tls import get_ssl_context, process_to_context @@ -1133,12 +1133,18 @@ def serve( manager.run() except ServerKilled: exit_code = 1 + except SanicException as e: + exit_code = 1 + kwargs = primary_server_info.settings + if e.quiet: + error_logger.error(str(e)) + else: + raise except BaseException: kwargs = primary_server_info.settings error_logger.exception( "Experienced exception while trying to serve" ) - raise finally: logger.info("Server Stopped") for app in apps: diff --git a/sanic/server/socket.py b/sanic/server/socket.py index a77e80a007..15b99ee5f9 100644 --- a/sanic/server/socket.py +++ b/sanic/server/socket.py @@ -47,10 +47,10 @@ def bind_unix_socket(path: str, *, mode=0o666, backlog=100) -> socket.socket: path = os.path.abspath(path) folder = os.path.dirname(path) if not os.path.isdir(folder): - raise FileNotFoundError(f"Socket folder does not exist: {folder}") + raise FileNotFoundError("Socket folder does not exist") try: if not stat.S_ISSOCK(os.stat(path, follow_symlinks=False).st_mode): - raise FileExistsError(f"Existing file is not a socket: {path}") + raise FileExistsError("Existing file is not a socket") except FileNotFoundError: pass # Create new socket with a random temporary name @@ -103,7 +103,10 @@ def configure_socket( unix = server_settings["unix"] backlog = server_settings["backlog"] if unix: - sock = bind_unix_socket(unix, backlog=backlog) + try: + sock = bind_unix_socket(unix, backlog=backlog) + except OSError as e: + raise ServerError(f"Error binding {unix}: {e}", quiet=True) server_settings["unix"] = unix if sock is None: try: @@ -112,6 +115,17 @@ def configure_socket( server_settings["port"], backlog=backlog, ) + except PermissionError: + p = server_settings["port"] + if not p or p >= 1024: + raise + addr = f"{server_settings['host']}:{p}" + error = ServerError( + f"Permission denied binding to {addr}.\n\n" + "Use `sudo sanic` to run on a privileged port.\n" + ) + error.quiet = True + raise error except OSError as e: # no cov error = ServerError( f"Sanic server could not start: {e}.\n\n"