Node not killed when an expcetion raised inside a timer_callback()

Hi,

  1. Normally, when the node has an exception, the node will die, shutdown,. …
    But when I raise an exception inside a timer_callback(). The node is not dead

Why? Please help

  1. I want to use respawn=“true” in a launch file to respawn a node if there is an exception while the node is working. The exception raised but the node is not dead → The node can not respawn.

Do you have any suggestions for this problem?

  1. Python file
#! /usr/bin/env python3

import rospy

from geometry_msgs.msg import Twist
from std_msgs.msg import Int32


class TopicPublisher():
    def __init__(self, nodeName):
        self.nodeName = nodeName
        rospy.init_node(name=nodeName, log_level=rospy.INFO)
        self.ctrlC = False
      
        # region init
        self.publisher  = rospy.Publisher(
            data_class  = Int32, 
            name        = 'topic_publisher',
            queue_size  = 10,
            latch       = False
        )
        self.int32_publisher = Int32()

        self.timer = rospy.Timer(rospy.Duration(2), self.timer_callback)
        # endregion
        
        self.logger.info(f"{self.nodeName} initialize successfully\n")
        
    def timer_callback(self, event):
        self.int32_publisher.data = self.int32_publisher.data + 1
        
        self.publisher.publish(self.int32_publisher)
        rospy.loginfo(f"self.int32_publisher.data: {self.int32_publisher.data}")

        if self.int32_publisher.data >= 5:
            raise Exception("User Exception")
            
    


def main(args=None):
    topicPublisher = TopicPublisher("topic_publisher_node")
    rospy.spin()


if __name__ == '__main__':
    main()
  1. Launch file
<launch>

    <!-- #region topic_publisher_node -->
    <node   name            = "topic_publisher_node"
            pkg             = "cmake_package" 
            type            = "_01_publisher.py"
            output          = "screen"
            respawn         = "true"
            respawn_delay   = "10"  
    >

    </node>
    <!-- #endregion -->    

</launch>

It’s because timer_callback is running in a separate thread. This is indicated in the image you attached:

Exception in thread Thread-x

Only an exception in the main thread would stop the node.

Raise the exception in the main thread when the condition is met. You could change your code as follows:

# Add to init
def __init__(self, nodeName):
  ...
  self.raise_exception = False

# Change timer callback
if self.int32_publisher.data >= 5:
  self.raise_exception = True

# Change the main thread
def main(args=None):
  topic_publisher = TopicPublisher("topic_publisher_node")
  while topic_publisher.raise_exception is False:
    self.logger.info("Everything is still fine")
  raise Exception("Something bad has happened)

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.