# How to handle \`Connection closed by server\` gracefully

**URL:** <https://discuss.ray.io/t/how-to-handle-connection-closed-by-server-gracefully/3650>\
**Category:** Ray Core\
**Created:** [September 28, 2021, 7:56am UTC](https://discuss.ray.io/t/how-to-handle-connection-closed-by-server-gracefully/3650 "2021-09-28T07:56:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Birger](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ray.io/birger/32/417_2.png) [@Birger](https://discuss.ray.io/u/Birger)\
**Post date:** [September 28, 2021, 7:56am UTC](https://discuss.ray.io/t/how-to-handle-connection-closed-by-server-gracefully/3650/1 "2021-09-28T07:56:32Z")

</div>

When the ray-head is stopped the clients that are connected to it print out some error messages and then exits with error code 1.

```auto
2021-09-28 09:45:46,184 INFO worker.py:800 -- Connecting to existing Ray cluster at address: 10.0.0.63:6379
2021-09-28 09:45:48,184 WARNING worker.py:1189 -- The autoscaler failed with the following error:
Terminated with signal 15
  File "/home/birger/.local/lib/python3.8/site-packages/ray/autoscaler/_private/monitor.py", line 416, in <module>
    monitor.run()
  File "/home/birger/.local/lib/python3.8/site-packages/ray/autoscaler/_private/monitor.py", line 317, in run
    self._run()
  File "/home/birger/.local/lib/python3.8/site-packages/ray/autoscaler/_private/monitor.py", line 234, in _run
    time.sleep(AUTOSCALER_UPDATE_INTERVAL_S)

2021-09-28 09:45:48,204 ERROR worker.py:1191 -- listen_error_messages_raylet: Connection closed by server.
2021-09-28 09:45:48,204 ERROR worker.py:468 -- print_logs: Connection closed by server.
2021-09-28 09:45:48,205 ERROR import_thread.py:88 -- ImportThread: Connection closed by server.

```

I would like to handle this error in our code, such that the application can exit gracefully. Is there any way in which that can be done?

---

<div class="post-metadata">

**Author:** ![yic](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ray.io/yic/32/437_2.png) [@yic](https://discuss.ray.io/u/yic)\
**Post date:** [September 29, 2021, 6:09am UTC](https://discuss.ray.io/t/how-to-handle-connection-closed-by-server-gracefully/3650/2 "2021-09-29T06:09:50Z")

</div>

Do you want to give something like this a try

```auto
import ray
import time
try:
┊ with ray.init("ray://"):
┊ ┊ time.sleep(10)
except ConnectionError as e :
┊ print("ERROR", e)

```

---

<div class="post-metadata">

**Author:** ![Birger](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ray.io/birger/32/417_2.png) [@Birger](https://discuss.ray.io/u/Birger)\
**Post date:** [September 29, 2021, 6:32am UTC](https://discuss.ray.io/t/how-to-handle-connection-closed-by-server-gracefully/3650/3 "2021-09-29T06:32:25Z")

</div>

Thanks 🙏 That did indeed work 😃 👏
