We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
BUG: yt crashes on startup if the config file is invalid toml
@cphyc originally noted this problem in #3831
```bash
echo "! this is invalid" > yt.toml 
python -c "import yt"
```
fails with the backtrace
```backtrace
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/XXX/Documents/prog/yt/yt/__init__.py", line 13, in <module>
    import yt.utilities.physical_constants as physical_constants
  File "/home/XXX/Documents/prog/yt/yt/utilities/physical_constants.py", line 3, in <module>
    from yt.units.yt_array import YTQuantity
  File "/home/XXX/Documents/prog/yt/yt/units/yt_array.py", line 3, in <module>
    from yt.funcs import array_like_field  # NOQA: F401
  File "/home/XXX/Documents/prog/yt/yt/funcs.py", line 33, in <module>
    from yt.utilities.logger import ytLogger as mylog
  File "/home/XXX/Documents/prog/yt/yt/utilities/logger.py", line 4, in <module>
    from yt.config import ytcfg
  File "/home/XXX/Documents/prog/yt/yt/config.py", line 215, in <module>
    ytcfg.read(_local_config_file)
  File "/home/XXX/Documents/prog/yt/yt/config.py", line 154, in read
    data = tomllib.load(fh)
  File "/home/XXX/anaconda3/envs/py39/lib/python3.9/site-packages/tomli/_parser.py", line 66, in load
    return loads(s, parse_float=parse_float)
  File "/home/XXX/anaconda3/envs/py39/lib/python3.9/site-packages/tomli/_parser.py", line 116, in loads
    raise suffixed_err(src, pos, "Invalid statement")
tomli.TOMLDecodeError: Invalid statement (at line 1, column 1)
```

_Originally posted by @cphyc in https://github.com/yt-project/yt/pull/3831#pullrequestreview-898674860_

We could embed this step in a `try/except` block and raise a warning instead of an error (still keeping the critical information from the original error).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `yt/utilities/configure.py`
Content:
```
1 import os
2 from typing import Callable, List
3 
4 # TODO: import tomllib from the standard library instead in Python >= 3.11
5 import tomli as tomllib
6 import tomli_w
7 from more_itertools import always_iterable
8 
9 from yt.utilities.configuration_tree import ConfigLeaf, ConfigNode
10 
11 configuration_callbacks: List[Callable[["YTConfig"], None]] = []
12 
13 
14 def config_dir():
15     config_root = os.environ.get(
16         "XDG_CONFIG_HOME", os.path.join(os.path.expanduser("~"), ".config")
17     )
18     conf_dir = os.path.join(config_root, "yt")
19     return conf_dir
20 
21 
22 class YTConfig:
23     def __init__(self, defaults=None):
24         if defaults is None:
25             defaults = {}
26         self.config_root = ConfigNode(None)
27 
28     def get(self, section, *keys, callback=None):
29         node_or_leaf = self.config_root.get(section, *keys)
30         if isinstance(node_or_leaf, ConfigLeaf):
31             if callback is not None:
32                 return callback(node_or_leaf)
33             return node_or_leaf.value
34         return node_or_leaf
35 
36     def get_most_specific(self, section, *keys, **kwargs):
37         use_fallback = "fallback" in kwargs
38         fallback = kwargs.pop("fallback", None)
39         try:
40             return self.config_root.get_deepest_leaf(section, *keys)
41         except KeyError as err:
42             if use_fallback:
43                 return fallback
44             else:
45                 raise err
46 
47     def update(self, new_values, metadata=None):
48         if metadata is None:
49             metadata = {}
50         self.config_root.update(new_values, metadata)
51 
52     def has_section(self, section):
53         try:
54             self.config_root.get_child(section)
55             return True
56         except KeyError:
57             return False
58 
59     def add_section(self, section):
60         self.config_root.add_child(section)
61 
62     def remove_section(self, section):
63         if self.has_section(section):
64             self.config_root.remove_child(section)
65             return True
66         else:
67             return False
68 
69     def set(self, *args, metadata=None):
70         section, *keys, value = args
71         if metadata is None:
72             metadata = {"source": "runtime"}
73         self.config_root.upsert_from_list(
74             [section] + list(keys), value, extra_data=metadata
75         )
76 
77     def remove(self, *args):
78         self.config_root.pop_leaf(args)
79 
80     def read(self, file_names):
81         file_names_read = []
82         for fname in always_iterable(file_names):
83             if not os.path.exists(fname):
84                 continue
85             metadata = {"source": f"file: {fname}"}
86             with open(fname, "rb") as fh:
87                 data = tomllib.load(fh)
88             self.update(data, metadata=metadata)
89             file_names_read.append(fname)
90 
91         return file_names_read
92 
93     def write(self, file_handler):
94         value = self.config_root.as_dict()
95         config_as_str = tomli_w.dumps(value)
96 
97         try:
98             # Assuming file_handler has a write attribute
99             file_handler.write(config_as_str)
100         except AttributeError:
101             # Otherwise we expect a path to a file
102             with open(file_handler, mode="w") as fh:
103                 fh.write(config_as_str)
104 
105     @staticmethod
106     def get_global_config_file():
107         return os.path.join(config_dir(), "yt.toml")
108 
109     @staticmethod
110     def get_local_config_file():
111         return os.path.join(os.path.abspath(os.curdir), "yt.toml")
112 
113     def __setitem__(self, args, value):
114         section, *keys = always_iterable(args)
115         self.set(section, *keys, value, metadata=None)
116 
117     def __getitem__(self, key):
118         section, *keys = always_iterable(key)
119         return self.get(section, *keys)
120 
121     def __contains__(self, item):
122         return item in self.config_root
123 
124     # Add support for IPython rich display
125     # see https://ipython.readthedocs.io/en/stable/config/integrating.html
126     def _repr_json_(self):
127         return self.config_root._repr_json_()
128 
129 
130 CONFIG = YTConfig()
131 
132 
133 def _cast_bool_helper(value):
134     if value == "True":
135         return True
136     elif value == "False":
137         return False
138     else:
139         raise ValueError("Cannot safely cast to bool")
140 
141 
142 def _expand_all(s):
143     return os.path.expandvars(os.path.expanduser(s))
144 
145 
146 def _cast_value_helper(value, types=(_cast_bool_helper, int, float, _expand_all)):
147     for t in types:
148         try:
149             retval = t(value)
150             return retval
151         except ValueError:
152             pass
153 
154 
155 def get_config(section, option):
156     *option_path, option_name = option.split(".")
157     return CONFIG.get(section, *option_path, option_name)
158 
159 
160 def set_config(section, option, value, config_file):
161     if not CONFIG.has_section(section):
162         CONFIG.add_section(section)
163 
164     option_path = option.split(".")
165     CONFIG.set(section, *option_path, _cast_value_helper(value))
166     write_config(config_file)
167 
168 
169 def write_config(config_file):
170     CONFIG.write(config_file)
171 
172 
173 def rm_config(section, option, config_file):
174     option_path = option.split(".")
175     CONFIG.remove(section, *option_path)
176     write_config(config_file)
177
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/yt/utilities/configure.py b/yt/utilities/configure.py
--- a/yt/utilities/configure.py
+++ b/yt/utilities/configure.py
@@ -1,4 +1,5 @@
 import os
+import warnings
 from typing import Callable, List
 
 # TODO: import tomllib from the standard library instead in Python >= 3.11
@@ -83,10 +84,16 @@
             if not os.path.exists(fname):
                 continue
             metadata = {"source": f"file: {fname}"}
-            with open(fname, "rb") as fh:
-                data = tomllib.load(fh)
-            self.update(data, metadata=metadata)
-            file_names_read.append(fname)
+            try:
+                with open(fname, "rb") as fh:
+                    data = tomllib.load(fh)
+            except tomllib.TOMLDecodeError as exc:
+                warnings.warn(
+                    f"Could not load configuration file {fname} (invalid TOML: {exc})"
+                )
+            else:
+                self.update(data, metadata=metadata)
+                file_names_read.append(fname)
 
         return file_names_read

{"golden_diff": "diff --git a/yt/utilities/configure.py b/yt/utilities/configure.py\n--- a/yt/utilities/configure.py\n+++ b/yt/utilities/configure.py\n@@ -1,4 +1,5 @@\n import os\n+import warnings\n from typing import Callable, List\n \n # TODO: import tomllib from the standard library instead in Python >= 3.11\n@@ -83,10 +84,16 @@\n             if not os.path.exists(fname):\n                 continue\n             metadata = {\"source\": f\"file: {fname}\"}\n-            with open(fname, \"rb\") as fh:\n-                data = tomllib.load(fh)\n-            self.update(data, metadata=metadata)\n-            file_names_read.append(fname)\n+            try:\n+                with open(fname, \"rb\") as fh:\n+                    data = tomllib.load(fh)\n+            except tomllib.TOMLDecodeError as exc:\n+                warnings.warn(\n+                    f\"Could not load configuration file {fname} (invalid TOML: {exc})\"\n+                )\n+            else:\n+                self.update(data, metadata=metadata)\n+                file_names_read.append(fname)\n \n         return file_names_read\n", "issue": "BUG: yt crashes on startup if the config file is invalid toml\n@cphyc originally noted this problem in #3831\r\n```bash\r\necho \"! this is invalid\" > yt.toml \r\npython -c \"import yt\"\r\n```\r\nfails with the backtrace\r\n```backtrace\r\nTraceback (most recent call last):\r\n  File \"<string>\", line 1, in <module>\r\n  File \"/home/XXX/Documents/prog/yt/yt/__init__.py\", line 13, in <module>\r\n    import yt.utilities.physical_constants as physical_constants\r\n  File \"/home/XXX/Documents/prog/yt/yt/utilities/physical_constants.py\", line 3, in <module>\r\n    from yt.units.yt_array import YTQuantity\r\n  File \"/home/XXX/Documents/prog/yt/yt/units/yt_array.py\", line 3, in <module>\r\n    from yt.funcs import array_like_field  # NOQA: F401\r\n  File \"/home/XXX/Documents/prog/yt/yt/funcs.py\", line 33, in <module>\r\n    from yt.utilities.logger import ytLogger as mylog\r\n  File \"/home/XXX/Documents/prog/yt/yt/utilities/logger.py\", line 4, in <module>\r\n    from yt.config import ytcfg\r\n  File \"/home/XXX/Documents/prog/yt/yt/config.py\", line 215, in <module>\r\n    ytcfg.read(_local_config_file)\r\n  File \"/home/XXX/Documents/prog/yt/yt/config.py\", line 154, in read\r\n    data = tomllib.load(fh)\r\n  File \"/home/XXX/anaconda3/envs/py39/lib/python3.9/site-packages/tomli/_parser.py\", line 66, in load\r\n    return loads(s, parse_float=parse_float)\r\n  File \"/home/XXX/anaconda3/envs/py39/lib/python3.9/site-packages/tomli/_parser.py\", line 116, in loads\r\n    raise suffixed_err(src, pos, \"Invalid statement\")\r\ntomli.TOMLDecodeError: Invalid statement (at line 1, column 1)\r\n```\r\n\r\n_Originally posted by @cphyc in https://github.com/yt-project/yt/pull/3831#pullrequestreview-898674860_\r\n\r\nWe could embed this step in a `try/except` block and raise a warning instead of an error (still keeping the critical information from the original error).\n", "before_files": [{"content": "import os\nfrom typing import Callable, List\n\n# TODO: import tomllib from the standard library instead in Python >= 3.11\nimport tomli as tomllib\nimport tomli_w\nfrom more_itertools import always_iterable\n\nfrom yt.utilities.configuration_tree import ConfigLeaf, ConfigNode\n\nconfiguration_callbacks: List[Callable[[\"YTConfig\"], None]] = []\n\n\ndef config_dir():\n    config_root = os.environ.get(\n        \"XDG_CONFIG_HOME\", os.path.join(os.path.expanduser(\"~\"), \".config\")\n    )\n    conf_dir = os.path.join(config_root, \"yt\")\n    return conf_dir\n\n\nclass YTConfig:\n    def __init__(self, defaults=None):\n        if defaults is None:\n            defaults = {}\n        self.config_root = ConfigNode(None)\n\n    def get(self, section, *keys, callback=None):\n        node_or_leaf = self.config_root.get(section, *keys)\n        if isinstance(node_or_leaf, ConfigLeaf):\n            if callback is not None:\n                return callback(node_or_leaf)\n            return node_or_leaf.value\n        return node_or_leaf\n\n    def get_most_specific(self, section, *keys, **kwargs):\n        use_fallback = \"fallback\" in kwargs\n        fallback = kwargs.pop(\"fallback\", None)\n        try:\n            return self.config_root.get_deepest_leaf(section, *keys)\n        except KeyError as err:\n            if use_fallback:\n                return fallback\n            else:\n                raise err\n\n    def update(self, new_values, metadata=None):\n        if metadata is None:\n            metadata = {}\n        self.config_root.update(new_values, metadata)\n\n    def has_section(self, section):\n        try:\n            self.config_root.get_child(section)\n            return True\n        except KeyError:\n            return False\n\n    def add_section(self, section):\n        self.config_root.add_child(section)\n\n    def remove_section(self, section):\n        if self.has_section(section):\n            self.config_root.remove_child(section)\n            return True\n        else:\n            return False\n\n    def set(self, *args, metadata=None):\n        section, *keys, value = args\n        if metadata is None:\n            metadata = {\"source\": \"runtime\"}\n        self.config_root.upsert_from_list(\n            [section] + list(keys), value, extra_data=metadata\n        )\n\n    def remove(self, *args):\n        self.config_root.pop_leaf(args)\n\n    def read(self, file_names):\n        file_names_read = []\n        for fname in always_iterable(file_names):\n            if not os.path.exists(fname):\n                continue\n            metadata = {\"source\": f\"file: {fname}\"}\n            with open(fname, \"rb\") as fh:\n                data = tomllib.load(fh)\n            self.update(data, metadata=metadata)\n            file_names_read.append(fname)\n\n        return file_names_read\n\n    def write(self, file_handler):\n        value = self.config_root.as_dict()\n        config_as_str = tomli_w.dumps(value)\n\n        try:\n            # Assuming file_handler has a write attribute\n            file_handler.write(config_as_str)\n        except AttributeError:\n            # Otherwise we expect a path to a file\n            with open(file_handler, mode=\"w\") as fh:\n                fh.write(config_as_str)\n\n    @staticmethod\n    def get_global_config_file():\n        return os.path.join(config_dir(), \"yt.toml\")\n\n    @staticmethod\n    def get_local_config_file():\n        return os.path.join(os.path.abspath(os.curdir), \"yt.toml\")\n\n    def __setitem__(self, args, value):\n        section, *keys = always_iterable(args)\n        self.set(section, *keys, value, metadata=None)\n\n    def __getitem__(self, key):\n        section, *keys = always_iterable(key)\n        return self.get(section, *keys)\n\n    def __contains__(self, item):\n        return item in self.config_root\n\n    # Add support for IPython rich display\n    # see https://ipython.readthedocs.io/en/stable/config/integrating.html\n    def _repr_json_(self):\n        return self.config_root._repr_json_()\n\n\nCONFIG = YTConfig()\n\n\ndef _cast_bool_helper(value):\n    if value == \"True\":\n        return True\n    elif value == \"False\":\n        return False\n    else:\n        raise ValueError(\"Cannot safely cast to bool\")\n\n\ndef _expand_all(s):\n    return os.path.expandvars(os.path.expanduser(s))\n\n\ndef _cast_value_helper(value, types=(_cast_bool_helper, int, float, _expand_all)):\n    for t in types:\n        try:\n            retval = t(value)\n            return retval\n        except ValueError:\n            pass\n\n\ndef get_config(section, option):\n    *option_path, option_name = option.split(\".\")\n    return CONFIG.get(section, *option_path, option_name)\n\n\ndef set_config(section, option, value, config_file):\n    if not CONFIG.has_section(section):\n        CONFIG.add_section(section)\n\n    option_path = option.split(\".\")\n    CONFIG.set(section, *option_path, _cast_value_helper(value))\n    write_config(config_file)\n\n\ndef write_config(config_file):\n    CONFIG.write(config_file)\n\n\ndef rm_config(section, option, config_file):\n    option_path = option.split(\".\")\n    CONFIG.remove(section, *option_path)\n    write_config(config_file)\n", "path": "yt/utilities/configure.py"}], "after_files": [{"content": "import os\nimport warnings\nfrom typing import Callable, List\n\n# TODO: import tomllib from the standard library instead in Python >= 3.11\nimport tomli as tomllib\nimport tomli_w\nfrom more_itertools import always_iterable\n\nfrom yt.utilities.configuration_tree import ConfigLeaf, ConfigNode\n\nconfiguration_callbacks: List[Callable[[\"YTConfig\"], None]] = []\n\n\ndef config_dir():\n    config_root = os.environ.get(\n        \"XDG_CONFIG_HOME\", os.path.join(os.path.expanduser(\"~\"), \".config\")\n    )\n    conf_dir = os.path.join(config_root, \"yt\")\n    return conf_dir\n\n\nclass YTConfig:\n    def __init__(self, defaults=None):\n        if defaults is None:\n            defaults = {}\n        self.config_root = ConfigNode(None)\n\n    def get(self, section, *keys, callback=None):\n        node_or_leaf = self.config_root.get(section, *keys)\n        if isinstance(node_or_leaf, ConfigLeaf):\n            if callback is not None:\n                return callback(node_or_leaf)\n            return node_or_leaf.value\n        return node_or_leaf\n\n    def get_most_specific(self, section, *keys, **kwargs):\n        use_fallback = \"fallback\" in kwargs\n        fallback = kwargs.pop(\"fallback\", None)\n        try:\n            return self.config_root.get_deepest_leaf(section, *keys)\n        except KeyError as err:\n            if use_fallback:\n                return fallback\n            else:\n                raise err\n\n    def update(self, new_values, metadata=None):\n        if metadata is None:\n            metadata = {}\n        self.config_root.update(new_values, metadata)\n\n    def has_section(self, section):\n        try:\n            self.config_root.get_child(section)\n            return True\n        except KeyError:\n            return False\n\n    def add_section(self, section):\n        self.config_root.add_child(section)\n\n    def remove_section(self, section):\n        if self.has_section(section):\n            self.config_root.remove_child(section)\n            return True\n        else:\n            return False\n\n    def set(self, *args, metadata=None):\n        section, *keys, value = args\n        if metadata is None:\n            metadata = {\"source\": \"runtime\"}\n        self.config_root.upsert_from_list(\n            [section] + list(keys), value, extra_data=metadata\n        )\n\n    def remove(self, *args):\n        self.config_root.pop_leaf(args)\n\n    def read(self, file_names):\n        file_names_read = []\n        for fname in always_iterable(file_names):\n            if not os.path.exists(fname):\n                continue\n            metadata = {\"source\": f\"file: {fname}\"}\n            try:\n                with open(fname, \"rb\") as fh:\n                    data = tomllib.load(fh)\n            except tomllib.TOMLDecodeError as exc:\n                warnings.warn(\n                    f\"Could not load configuration file {fname} (invalid TOML: {exc})\"\n                )\n            else:\n                self.update(data, metadata=metadata)\n                file_names_read.append(fname)\n\n        return file_names_read\n\n    def write(self, file_handler):\n        value = self.config_root.as_dict()\n        config_as_str = tomli_w.dumps(value)\n\n        try:\n            # Assuming file_handler has a write attribute\n            file_handler.write(config_as_str)\n        except AttributeError:\n            # Otherwise we expect a path to a file\n            with open(file_handler, mode=\"w\") as fh:\n                fh.write(config_as_str)\n\n    @staticmethod\n    def get_global_config_file():\n        return os.path.join(config_dir(), \"yt.toml\")\n\n    @staticmethod\n    def get_local_config_file():\n        return os.path.join(os.path.abspath(os.curdir), \"yt.toml\")\n\n    def __setitem__(self, args, value):\n        section, *keys = always_iterable(args)\n        self.set(section, *keys, value, metadata=None)\n\n    def __getitem__(self, key):\n        section, *keys = always_iterable(key)\n        return self.get(section, *keys)\n\n    def __contains__(self, item):\n        return item in self.config_root\n\n    # Add support for IPython rich display\n    # see https://ipython.readthedocs.io/en/stable/config/integrating.html\n    def _repr_json_(self):\n        return self.config_root._repr_json_()\n\n\nCONFIG = YTConfig()\n\n\ndef _cast_bool_helper(value):\n    if value == \"True\":\n        return True\n    elif value == \"False\":\n        return False\n    else:\n        raise ValueError(\"Cannot safely cast to bool\")\n\n\ndef _expand_all(s):\n    return os.path.expandvars(os.path.expanduser(s))\n\n\ndef _cast_value_helper(value, types=(_cast_bool_helper, int, float, _expand_all)):\n    for t in types:\n        try:\n            retval = t(value)\n            return retval\n        except ValueError:\n            pass\n\n\ndef get_config(section, option):\n    *option_path, option_name = option.split(\".\")\n    return CONFIG.get(section, *option_path, option_name)\n\n\ndef set_config(section, option, value, config_file):\n    if not CONFIG.has_section(section):\n        CONFIG.add_section(section)\n\n    option_path = option.split(\".\")\n    CONFIG.set(section, *option_path, _cast_value_helper(value))\n    write_config(config_file)\n\n\ndef write_config(config_file):\n    CONFIG.write(config_file)\n\n\ndef rm_config(section, option, config_file):\n    option_path = option.split(\".\")\n    CONFIG.remove(section, *option_path)\n    write_config(config_file)\n", "path": "yt/utilities/configure.py"}]}