简体   繁体   中英

Creating a step by step validation

I am trying to make a monitoring application for a FTP server using FTP4J (referred to as client in the code example).

It connects to a FTP, logs in, creates a file locally, uploads file, downloads file, validates the files are the same, cleans up files on ftp and locally and disconnects.

All this is already made but my question is how do I best log what has happened and break when an error is detected?

The simple solution I could think of was to make a Boolean that shows if previous steps where successful and only do next step if they where.

StringBuilder sb = new StringBuilder();
boolean noError = true;
// Connect to FTP
try {
    client.connect(hostname, port);
} catch (Exception e) {
    noError = false;
    sb.append("failed to connect<br>");
}

//Logging in to FTP
if(noError) {
    try {
        client.login(username, password);

    } catch (Exception e) {
        noError = false;
        sb.append("failed to login<br>");
    }
}
...
// Close connection
if(client.isConnected()) {
    try {
        client.disconnect(true);
    } catch (Exception e) {
        sb.append("failed to disconnect<br>");
    }
}

another solution I could think of was nested try/catch but that looked even worse, is there a better way of doing this?

The solution is simple: don't catch the exception. As soon as an exception is thrown and is not caught, the whole process will stop. Or catch it but transform it into your own exception with the appropriate error message, and throw this exception.

Side note: you should use a boolean and not a Boolean to store a non-nullable boolean value.

StringBuilder sb = new StringBuilder();
Boolean noError = true;
// Connect to FTP
try {
    client.connect(hostname, port);
        client.login(username, password);

} catch (ConnectException ce) {
    sb.append("Couldn't connect: ");
    sb.append(ce.getMessage);
} catch (LoginException le) {
     sb.append("Couldn't login: ");
    sb.append(le.getMessage);

} finally {
if(client.isConnected()) {
    try {
        client.disconnect(true);
    } catch (Exception e) {
        sb.append("failed to disconnect<br>");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM