fix: Remove empty catch blocks and add error logging

This commit is contained in:
ZacharyZcR
2025-11-09 04:03:18 +08:00
parent c69d31062e
commit d7bbad89c3
21 changed files with 213 additions and 52 deletions

View File

@@ -1480,13 +1480,17 @@ app.get(
if (status.hasUnencryptedDb) {
try {
unencryptedSize = fs.statSync(dbPath).size;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
}
if (status.hasEncryptedDb) {
try {
encryptedSize = fs.statSync(encryptedDbPath).size;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
}
res.json({

View File

@@ -935,7 +935,9 @@ router.post("/login", async (req, res) => {
if (kekSalt.length === 0) {
await authManager.registerUser(userRecord.id, password);
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
const dataUnlocked = await authManager.authenticateUser(
userRecord.id,
@@ -1016,7 +1018,15 @@ router.post("/logout", authenticateJWT, async (req, res) => {
try {
const payload = await authManager.verifyJWTToken(token);
sessionId = payload?.sessionId;
} catch (error) {}
} catch (error) {
authLogger.debug(
"Token verification failed during logout (expected if token expired)",
{
operation: "logout_token_verify_failed",
userId,
},
);
}
}
await authManager.logoutUser(userId, sessionId);

View File

@@ -120,7 +120,9 @@ function cleanupSession(sessionId: string) {
if (session) {
try {
session.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
clearTimeout(session.timeout);
delete sshSessions[sessionId];
}
@@ -663,7 +665,9 @@ app.post("/ssh/file_manager/ssh/connect-totp", async (req, res) => {
delete pendingTOTPSessions[sessionId];
try {
session.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
fileLogger.warn("TOTP session timeout before code submission", {
operation: "file_totp_verify",
sessionId,

View File

@@ -156,7 +156,9 @@ class SSHConnectionPool {
if (!conn.inUse && now - conn.lastUsed > maxAge) {
try {
conn.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
return false;
}
return true;
@@ -176,7 +178,9 @@ class SSHConnectionPool {
for (const conn of connections) {
try {
conn.client.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
}
}
this.connections.clear();
@@ -214,7 +218,9 @@ class RequestQueue {
if (request) {
try {
await request();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
}
}
@@ -511,7 +517,14 @@ class PollingManager {
data: metrics,
timestamp: Date.now(),
});
} catch (error) {}
} catch (error) {
statsLogger.warn("Failed to collect metrics for host", {
operation: "metrics_poll_failed",
hostId: host.id,
hostName: host.name,
error: error instanceof Error ? error.message : String(error),
});
}
}
stopPollingForHost(hostId: number): void {
@@ -1212,7 +1225,12 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
txBytes: null,
});
}
} catch (e) {}
} catch (e) {
statsLogger.debug("Failed to collect network interface stats", {
operation: "network_stats_failed",
error: e instanceof Error ? e.message : String(e),
});
}
let uptimeSeconds: number | null = null;
let uptimeFormatted: string | null = null;
@@ -1228,7 +1246,12 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
uptimeFormatted = `${days}d ${hours}h ${minutes}m`;
}
}
} catch (e) {}
} catch (e) {
statsLogger.debug("Failed to collect uptime", {
operation: "uptime_failed",
error: e instanceof Error ? e.message : String(e),
});
}
let totalProcesses: number | null = null;
let runningProcesses: number | null = null;
@@ -1270,7 +1293,12 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
);
totalProcesses = Number(procCount.stdout.trim()) - 1;
runningProcesses = Number(runningCount.stdout.trim());
} catch (e) {}
} catch (e) {
statsLogger.debug("Failed to collect process stats", {
operation: "process_stats_failed",
error: e instanceof Error ? e.message : String(e),
});
}
let hostname: string | null = null;
let kernel: string | null = null;
@@ -1286,7 +1314,12 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
hostname = hostnameOut.stdout.trim() || null;
kernel = kernelOut.stdout.trim() || null;
os = osOut.stdout.trim() || null;
} catch (e) {}
} catch (e) {
statsLogger.debug("Failed to collect system info", {
operation: "system_info_failed",
error: e instanceof Error ? e.message : String(e),
});
}
const result = {
cpu: { percent: toFixedNum(cpuPercent, 0), cores, load: loadTriplet },
@@ -1365,7 +1398,9 @@ function tcpPing(
settled = true;
try {
socket.destroy();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
resolve(result);
};

View File

@@ -217,7 +217,9 @@ function cleanupTunnelResources(
if (verification?.timeout) clearTimeout(verification.timeout);
try {
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}
@@ -282,7 +284,9 @@ function handleDisconnect(
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}
@@ -638,7 +642,9 @@ async function connectSSHTunnel(
try {
conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
activeTunnels.delete(tunnelName);
@@ -778,7 +784,9 @@ async function connectSSHTunnel(
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
verification?.conn.end();
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", { error });
}
tunnelVerifications.delete(tunnelName);
}

View File

@@ -21,7 +21,11 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
if (persistentConfig.parsed) {
Object.assign(process.env, persistentConfig.parsed);
}
} catch {}
} catch (error) {
systemLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
let version = "unknown";

View File

@@ -233,7 +233,11 @@ IP.3 = 0.0.0.0
let envContent = "";
try {
envContent = await fs.readFile(this.ENV_FILE, "utf8");
} catch {}
} catch (error) {
systemLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
let updatedContent = envContent;
let hasChanges = false;

View File

@@ -327,7 +327,11 @@ class DatabaseFileEncryption {
fs.accessSync(envPath, fs.constants.R_OK);
envFileReadable = true;
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
databaseLogger.error(
"Database decryption authentication failed - possible causes: wrong DATABASE_KEY, corrupted files, or interrupted write",
@@ -628,7 +632,11 @@ class DatabaseFileEncryption {
try {
fs.accessSync(envPath, fs.constants.R_OK);
result.environment.envFileReadable = true;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
if (

View File

@@ -82,7 +82,11 @@ export class LazyFieldEncryption {
legacyFieldName,
);
return decrypted;
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
const sensitiveFields = [
@@ -174,7 +178,11 @@ export class LazyFieldEncryption {
wasPlaintext: false,
wasLegacyEncryption: true,
};
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
return {
encrypted: fieldValue,

View File

@@ -84,7 +84,11 @@ function detectKeyTypeFromContent(keyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519";
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 800) {
return "ssh-ed25519";
@@ -140,7 +144,11 @@ function detectPublicKeyTypeFromContent(publicKeyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519";
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 400) {
return "ssh-ed25519";
@@ -242,7 +250,11 @@ export function parseSSHKey(
useSSH2 = true;
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
}
if (!useSSH2) {
@@ -268,7 +280,11 @@ export function parseSSHKey(
success: true,
};
}
} catch {}
} catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
return {
privateKey: privateKeyData,

View File

@@ -51,7 +51,15 @@ class SystemCrypto {
},
);
}
} catch (fileError) {}
} catch (fileError) {
// OK: .env file not found or unreadable, will generate new JWT secret
databaseLogger.debug(
".env file not accessible, will generate new JWT secret",
{
operation: "jwt_env_not_found",
},
);
}
await this.generateAndGuideUser();
} catch (error) {
@@ -102,7 +110,15 @@ class SystemCrypto {
return;
} else {
}
} catch (fileError) {}
} catch (fileError) {
// OK: .env file not found or unreadable, will generate new database key
databaseLogger.debug(
".env file not accessible, will generate new database key",
{
operation: "db_key_env_not_found",
},
);
}
await this.generateAndGuideDatabaseKey();
} catch (error) {
@@ -140,7 +156,11 @@ class SystemCrypto {
process.env.INTERNAL_AUTH_TOKEN = tokenMatch[1];
return;
}
} catch {}
} catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
await this.generateAndGuideInternalAuthToken();
} catch (error) {

View File

@@ -91,7 +91,9 @@ export function Dashboard({
try {
const sidebar = useSidebar();
sidebarState = sidebar.state;
} catch {}
} catch (error) {
console.error("Dashboard operation failed:", error);
}
const topMarginPx = isTopbarOpen ? 74 : 26;
const leftMarginPx = sidebarState === "collapsed" ? 26 : 8;
@@ -173,7 +175,9 @@ export function Dashboard({
if (Array.isArray(tunnelConnections)) {
totalTunnelsCount += tunnelConnections.length;
}
} catch {}
} catch (error) {
console.error("Dashboard operation failed:", error);
}
}
}
setTotalTunnels(totalTunnelsCount);

View File

@@ -167,7 +167,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations);
} catch {}
} catch (error) {
console.error("Host manager operation failed:", error);
}
};
fetchData();
@@ -196,7 +198,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations);
} catch {}
} catch (error) {
console.error("Host manager operation failed:", error);
}
};
window.addEventListener("credentials:changed", handleCredentialChange);

View File

@@ -189,7 +189,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal as { refresh?: (start: number, end: number) => void }
).refresh(0, terminal.rows - 1);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
}
function performFit() {
@@ -331,7 +333,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
scheduleNotify(cols, rows);
hardRefresh();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
},
refresh: () => hardRefresh(),
}),
@@ -738,7 +742,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
await navigator.clipboard.writeText(text);
return;
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
@@ -758,7 +764,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
if (navigator.clipboard && navigator.clipboard.readText) {
return await navigator.clipboard.readText();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
return "";
}
@@ -855,7 +863,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
const pasteText = await readTextFromClipboard();
if (pasteText) terminal.paste(pasteText);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
};
element?.addEventListener("contextmenu", handleContextMenu);

View File

@@ -63,7 +63,9 @@ export function ElectronLoginForm({
}
}
}
} catch (err) {}
} catch (err) {
console.error("Authentication operation failed:", err);
}
};
window.addEventListener("message", handleMessage);
@@ -190,8 +192,12 @@ export function ElectronLoginForm({
);
}
}
} catch (err) {}
} catch (err) {}
} catch (err) {
console.error("Authentication operation failed:", err);
}
} catch (err) {
console.error("Authentication operation failed:", err);
}
};
const handleError = () => {

View File

@@ -37,7 +37,9 @@ export function ElectronServerConfig({
if (config?.serverUrl) {
setServerUrl(config.serverUrl);
}
} catch {}
} catch (error) {
console.error("Server config operation failed:", error);
}
};
const handleSaveConfig = async () => {

View File

@@ -54,7 +54,9 @@ async function handleLogout() {
},
serverOrigin,
);
} catch (err) {}
} catch (err) {
console.error("User profile operation failed:", err);
}
}
}
}

View File

@@ -48,7 +48,9 @@ export function useDragToSystemDesktop({ sshSessionId }: UseDragToSystemProps) {
store.put({ handle: dirHandle }, "lastSaveDir");
};
}
} catch {}
} catch (error) {
console.error("Drag operation failed:", error);
}
};
const isFileSystemAPISupported = () => {

View File

@@ -101,7 +101,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal as { refresh?: (start: number, end: number) => void }
).refresh(0, terminal.rows - 1);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
}
function performFit() {
@@ -175,7 +177,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
scheduleNotify(cols, rows);
hardRefresh();
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
},
refresh: () => hardRefresh(),
}),
@@ -225,7 +229,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
`\r\n[${msg.message || t("terminal.disconnected")}]`,
);
}
} catch {}
} catch (error) {
console.error("Terminal operation failed:", error);
}
});
ws.addEventListener("close", (event) => {

View File

@@ -110,7 +110,9 @@ export function TerminalKeyboard({
if (navigator.vibrate) {
navigator.vibrate(20);
}
} catch {}
} catch (error) {
console.error("Keyboard operation failed:", error);
}
onSendInput(input);
},

View File

@@ -52,7 +52,9 @@ function postJWTToWebView() {
timestamp: Date.now(),
}),
);
} catch (error) {}
} catch (error) {
console.error("Auth operation failed:", error);
}
}
interface AuthProps extends React.ComponentProps<"div"> {