Enhance SFTP error handling in SftpController and SftpService by introducing a method to format SftpException messages. Improve listFiles method to handle empty paths and provide clearer error messages in response to exceptions.

This commit is contained in:
liumangmang
2026-02-04 14:43:54 +08:00
parent a1b8a4af8c
commit 7f57d69756
2 changed files with 71 additions and 15 deletions

View File

@@ -1,5 +1,6 @@
package com.sshmanager.controller;
import com.jcraft.jsch.SftpException;
import com.sshmanager.dto.SftpFileInfo;
import com.sshmanager.entity.Connection;
import com.sshmanager.entity.User;
@@ -78,13 +79,28 @@ public class SftpController {
.collect(Collectors.toList());
return ResponseEntity.ok(dtos);
} catch (Exception e) {
log.warn("SFTP list failed: connectionId={}, path={}", connectionId, path, e);
String errorMsg = toSftpErrorMessage(e, path, "list");
log.warn("SFTP list failed: connectionId={}, path={}, error={}", connectionId, path, errorMsg, e);
Map<String, String> err = new HashMap<>();
err.put("error", e.getMessage() != null ? e.getMessage() : "List failed");
err.put("error", errorMsg);
return ResponseEntity.status(500).body(err);
}
}
private String toSftpErrorMessage(Exception e, String path, String operation) {
if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
return e.getMessage();
}
Throwable cause = e.getCause();
if (cause instanceof SftpException) {
return SftpService.formatSftpExceptionMessage((SftpException) cause, path, operation);
}
if (e instanceof SftpException) {
return SftpService.formatSftpExceptionMessage((SftpException) e, path, operation);
}
return operation + " failed";
}
@GetMapping("/pwd")
public ResponseEntity<Map<String, String>> pwd(
@RequestParam Long connectionId,