简体   繁体   English

创建一步一步验证

[英]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). 我正在尝试使用FTP4J (在代码示例中称为客户端)为FTP服务器创建监视应用程序。

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. 它连接到FTP,登录,在本地创建文件,上传文件,下载文件,验证文件是否相同,清理ftp和本地文件并断开连接。

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? 我能想到的另一个解决方案是嵌套的try / catch,但看起来更糟糕,有没有更好的方法呢?

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. 旁注:您应该使用boolean而不是Boolean来存储不可为空的布尔值。

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>");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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