我必须检查上传的防毒文件,如果有异常,我必须根据异常给用户一个消息。如果这是一个超时,我会要求用户尝试一下。
public class FileUpload {
//Message when no virus found.
private static final String NO_VIRUS_FOUND = "No virus found";
//More attributes and functions
public void checkFile(FacesContext ctx, UIComponent comp, Object value) throws IOException {
file = (Part) value;
if (file != null) {
String antiVirusResult;
antiVirusResult = FileCheckClass.checkVirus(getConfig(), file.getInputStream(), NO_VIRUS_FOUND);
if (!antiVirusResult.contains(NO_VIRUS_FOUND)) {
generateAntiVirusMessages(antiVirusResult);
throw new ValidatorException(msgs);
}
}
}
}public static String checkVirus(FileConfig fileconfig, InputStream inputStream, String noVirusFound) {
try {
ClamAVClient cl = new ClamAVClient(fileConfig.getClamavHost(), fileConfig.getClamavPort(), DEFAULT_TIMEOUT);
if(ClamAVClient.isCleanReply(cl.scan(inputStream))){
return noVirusFound;
}
} catch (Exception e) {
logger.error("Error while scanning file: ", e);
return e.toString();
}
return noVirusFound;
}从check函数中,我必须返回一个字符串,以便从第一个类将NO_VIRUS_FOUND传递给它。
发布于 2018-04-10 11:33:46
ClamAVClient.isCleanReply()返回false,但没有抛出异常,该怎么办?这里没有其他子句,而且checkVirus将不会返回找到的病毒。String,为什么checkVirus()不重新抛出异常?这样,它还可以返回病毒名称的字符串(或从ClamAVClient生成的任何内容)。FileUpload.NO_VIRUS_FOUND。VIRUS_FOUND .)虽然有争议,但异常编码被认为是一种反模式。异常应保留为错误条件,而不是作为发现病毒的指示。
关于如何实现pt 2的问题:首先,我将创建一个custum异常,表示病毒检查失败。
public class VirusCheckException extends Exception {
public VirusCheckException(Throwable cause) {
super(cause);
}
public VirusCheckException(String message, Throwable cause) {
super(message, cause);
}
// also rest of constructors...
}然后,抛出自定义异常,而不是返回异常消息。返回值被释放为从扫描返回更多丰富的数据(如果可能的话):
public static String checkVirus(FileConfig fileconfig, InputStream inputStream, String noVirusFound)
throws VirusCheckException {
try {
ClamAVClient cl = new ClamAVClient(fileConfig.getClamavHost(), fileConfig.getClamavPort(), DEFAULT_TIMEOUT);
Object response = cl.scan(inputStream);
if (ClamAVClient.isCleanReply(response)) {
return noVirusFound;
} else {
return ClamAVClient.getVirusName(response); // assuming there is such...
}
} catch (Exception e) {
return new VirusCheckException("Virus Found!", e);
}
}现在,您必须在callng方法中捕获该异常并处理它:
public void checkFile(...) {
try {
antiVirusResult = FileCheckClass.checkVirus(getConfig(), file.getInputStream(), NO_VIRUS_FOUND);
} catch (VirusCheckException e) {
generateAntiVirusMessages(e.getMessage());
throw new ValidatorException(msgs);
}
}https://codereview.stackexchange.com/questions/191680
复制相似问题