spansh.py: rudimentary error handling

This commit is contained in:
alterNERDtive 2020-03-09 18:12:26 +01:00
parent 07a6db2595
commit 0054b5ae6c

View file

@ -7,6 +7,20 @@ import sys
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pyEDSM.edsm.exception import ServerError, NotFoundError
# ===========================================================================
def querystations(url, params):
response = requests.post(url, params)
if response.status_code != 200:
raise ServerError(url, params)
json = response.json()
if json["count"] == 0:
raise NotFoundError()
print(json)
return json
# =========================================================================== # ===========================================================================
def getNearestSystem(coords): def getNearestSystem(coords):
@ -15,7 +29,11 @@ def getNearestSystem(coords):
"y": coords[1], "y": coords[1],
"z": coords[2] "z": coords[2]
} }
json = requests.post(APIURLS["nearest"], params).json() response = requests.post(APIURLS["nearest"], params)
if response.status_code != 200:
raise ServerError(url, params)
json = response.json()
ret = None ret = None
system = json["system"] system = json["system"]
@ -39,7 +57,7 @@ def getOldStations():
"size": args.count "size": args.count
}) })
} }
json = requests.post(APIURLS["stations"], params).json() json = querystations(APIURLS["stations"], params)
ret = "" ret = ""
for station in json["results"]: for station in json["results"]:
@ -59,7 +77,7 @@ def getOldStationsInSystem(system):
"sort": SORT "sort": SORT
}) })
} }
json = requests.post(APIURLS["stations"], params).json() json = querystations(APIURLS["stations"], params)
ret = "" ret = ""
for station in json["results"]: for station in json["results"]:
@ -122,7 +140,7 @@ SORT = {
} }
} }
out = None try:
if args.subcommand == "nearestsystem": if args.subcommand == "nearestsystem":
out = getNearestSystem(args.coordinate) out = getNearestSystem(args.coordinate)
elif args.subcommand == "oldstations": elif args.subcommand == "oldstations":
@ -130,6 +148,12 @@ elif args.subcommand == "oldstations":
out = getOldStationsInSystem(args.system) out = getOldStationsInSystem(args.system)
else: else:
out = getOldStations() out = getOldStations()
except ServerError as e:
print(e)
sys.exit(1)
except NotFoundError as e:
print("No results found.")
sys.exit(2)
else:
print(out) print(out)
sys.exit(0) sys.exit(0)