Make an if statement if coordinates gives error. (Python)

Right now I have to far away coordinates, but I want to give it a default value, like if it gives me this error:

ApiError at /

400 ({‘error’: {‘code’: 2004, ‘message’: ‘Request parameters exceed the server configuration limits. The approximated route distance must not be greater than 6000000.0 meters.’}, ‘info’: {‘engine’: {‘version’: ‘6.6.1’, ‘build_date’: ‘2021-07-05T10:57:48Z’}, ‘timestamp’: 1635911707647}})

Instead of getting this error, is there a way to make an if statement, so that the coordinates gets a default Lat and Lng? So the error doesn’t show up, and that I can write down in the if statement something manually.

Hey,

this question is not related to the openrouteservice itself, but is a programming question related to python.
Please refer to the python documentation, tutorials or forums.

As the ApiError from the openrouteservice-py package is an exception, the try-statement could be what you’re looking for.

Best regards

1 Like

I can’t find any ApiError exception. What should I add instead?

This is what I tried, it didn’t work.

    try:
        coordinates = [[place[1], place[0]], [destination[1], destination[0]]]
    except:
        coordinates = [[35.222124, 31.777428], [35.225827, 31.775214]]

I also have tried adding except ApiError:. But it seems like it doesn’t exist.

What I mean with “it doesn’t exist”, is that when I add ApiError, The code editor highlighted it yellow.

Now I found solution

I read this Python Try Except

The error needs to come from the try.

coordinates is not what gives the error, but the thing that uses the coordinates when making the map.

So I added this instead:

    coordinates = [[place[1], place[0]], [destination[1], destination[0]]]

    try:
        # if it works
        route = klient.directions(coordinates=coordinates,
                            profile='driving-car',
                            format='geojson')
        folium.GeoJson(route, name='route').add_to(m)

    except:
        # if the coordinates doesn't work
        coordinates = [[35.222124, 31.777428], [35.225827, 31.775214]]

        route = klient.directions(coordinates=coordinates,
                            profile='driving-car',
                            format='geojson')
        folium.GeoJson(route, name='route').add_to(m)
2 Likes