Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly throw runtime exception and restart docker container

I have a Docker container with a Java application that uses a DB to persist some data. My application has a class that extends another one that is not code of mine (specifically SinkTask, a class from Kafka that is used to transfer data from Kafka to another system). When the application starts it opens a connection to the database. Sometimes, the database closes the connection and tasks start to fail. The exceptions thrown by these failures are catched in one part of my code and I can think of different ways to handle them: 1. Simply executing the code from within the application that stops and starts the connection again 2. Restarting the Docker container, creating a new connection in the process

I think the best solution is number 1. However, I wanted to know how could I trigger the second situation. My guess is that I should throw a new Exception in the catch block capable of terminating the application (remember that the SinkTask part of the code is out of my control). Would this be a good solution? Which kind of Exception should I throw in this case?

This is the part of the code where I catch the exception

    private void commitCollections() {
        for (SinkCollection sc : collections.values()) {
            try {
                commitCollection(sc);
            } catch (Exception e) {
                LOG.error("Error flushing collection " + sc.getTableName(), e);
            }
        }
        transactionRecordCount = 0;
        try {
            connection.commit();
        } catch (SQLException e) {
            LOG.error("Commit error", e);
        }
    }
like image 716
Brandon Avatar asked Oct 24 '25 04:10

Brandon


1 Answers

Throwing an Exception and letting it propagate in order to terminate the application is a perfectly nice solution. IMO, using System.exit(exit_code) would be better because it clearly describes what that code is doing.

In addition, docker will display the exit_code in the status of the container (docker ps -a), thus helping differentiate between different error conditions. When an uncaught exception is thrown the exit code is always 1.

Hope that helps.

like image 174
b0gusb Avatar answered Oct 25 '25 17:10

b0gusb