-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathexceptions.py
More file actions
52 lines (39 loc) · 1.25 KB
/
exceptions.py
File metadata and controls
52 lines (39 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Avoid this:
# import json
# def load_config(path):
# try:
# with open(path, encoding="utf-8") as config:
# data = json.load(config)
# except Exception:
# # If something went wrong, return an empty config
# return {}
# return data
# def main():
# try:
# config = load_config("settings.json")
# except Exception:
# print("Sorry, something went wrong.")
# # Do something with config...
# Favor this:
import json
import logging
log = logging.getLogger(__name__)
class ConfigError(Exception):
"""Raised when issues occur with config file."""
def load_config(path):
try:
with open(path, encoding="utf-8") as config:
data = json.load(config)
except FileNotFoundError as error:
raise ConfigError(f"Config file not found: {path}") from error
except json.JSONDecodeError as error:
raise ConfigError(f"Invalid JSON: {path}") from error
return data
def main():
try:
config = load_config("settings.json")
print("Config:", config)
except ConfigError as error:
log.error("Error loading the config: %s", error)
print("Sorry, something went wrong while loading the settings.")
# Do something with config...