Skip to content

FALLBACK_ERROR_FORMAT cannot be set even when the update_config function is called because the ErrorHandler object receives the default value of the config and is initialized. #2276

Closed
@SaidBySolo

Description

@SaidBySolo

Describe the bug

sanic/sanic/app.py

Lines 139 to 184 in 3262878

def __init__(
self,
name: str = None,
config: Optional[Config] = None,
ctx: Optional[Any] = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
load_env: Union[bool, str] = True,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[Type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[Dict[str, Any]] = None,
configure_logging: bool = True,
register: Optional[bool] = None,
dumps: Optional[Callable[..., AnyStr]] = None,
) -> None:
super().__init__(name=name)
# logging
if configure_logging:
logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)
if config and (load_env is not True or env_prefix != SANIC_PREFIX):
raise SanicException(
"When instantiating Sanic with config, you cannot also pass "
"load_env or env_prefix"
)
self._asgi_client = None
self._blueprint_order: List[Blueprint] = []
self._delayed_tasks: List[str] = []
self._test_client = None
self._test_manager = None
self.asgi = False
self.auto_reload = False
self.blueprints: Dict[str, Blueprint] = {}
self.config = config or Config(
load_env=load_env, env_prefix=env_prefix
)
self.configure_logging = configure_logging
self.ctx = ctx or SimpleNamespace()
self.debug = None
self.error_handler = error_handler or ErrorHandler(
fallback=self.config.FALLBACK_ERROR_FORMAT,
)

Referring to the code above, since the config is set when the Sanic object is initialized, you cannot pass a fallback value to the ErrorHandler even if you set config.update_config or app.config.FALLBACK_ERROR_FORMAT = "json".

To solve this, you can pass the config argument when initializing the Sanic app, but this doesn't seem to be intended.

Code snippet

app = Sanic(__name__)

@app.main_process_start
async def start(app, loop):
    app.config.FALLBACK_ERROR_FORMAT = "json"

Expected behavior
Even if you use config.update_config or app.config.FALLBACK_ERROR_FORMAT = "json", the error handler should normally receive this value.

Environment (please complete the following information):

  • OS: [Windows 10]
  • Version [21.9.1]

Additional context

I wanted to open a PR on this issue, but I'm not sure where to touch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions