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) { if (status.hasUnencryptedDb) {
try { try {
unencryptedSize = fs.statSync(dbPath).size; unencryptedSize = fs.statSync(dbPath).size;
} catch {} } catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
} }
if (status.hasEncryptedDb) { if (status.hasEncryptedDb) {
try { try {
encryptedSize = fs.statSync(encryptedDbPath).size; encryptedSize = fs.statSync(encryptedDbPath).size;
} catch {} } catch (error) {
databaseLogger.debug("Operation failed, continuing", { error });
}
} }
res.json({ res.json({

View File

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

View File

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

View File

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

View File

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

View File

@@ -21,7 +21,11 @@ import { systemLogger, versionLogger } from "./utils/logger.js";
if (persistentConfig.parsed) { if (persistentConfig.parsed) {
Object.assign(process.env, 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"; let version = "unknown";

View File

@@ -233,7 +233,11 @@ IP.3 = 0.0.0.0
let envContent = ""; let envContent = "";
try { try {
envContent = await fs.readFile(this.ENV_FILE, "utf8"); 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 updatedContent = envContent;
let hasChanges = false; let hasChanges = false;

View File

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

View File

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

View File

@@ -84,7 +84,11 @@ function detectKeyTypeFromContent(keyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) { } else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519"; return "ssh-ed25519";
} }
} catch {} } catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 800) { if (content.length < 800) {
return "ssh-ed25519"; return "ssh-ed25519";
@@ -140,7 +144,11 @@ function detectPublicKeyTypeFromContent(publicKeyContent: string): string {
} else if (decodedString.includes("1.3.101.112")) { } else if (decodedString.includes("1.3.101.112")) {
return "ssh-ed25519"; return "ssh-ed25519";
} }
} catch {} } catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
if (content.length < 400) { if (content.length < 400) {
return "ssh-ed25519"; return "ssh-ed25519";
@@ -242,7 +250,11 @@ export function parseSSHKey(
useSSH2 = true; useSSH2 = true;
} }
} catch {} } catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
} }
if (!useSSH2) { if (!useSSH2) {
@@ -268,7 +280,11 @@ export function parseSSHKey(
success: true, success: true,
}; };
} }
} catch {} } catch (error) {
sshLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
return { return {
privateKey: privateKeyData, 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(); await this.generateAndGuideUser();
} catch (error) { } catch (error) {
@@ -102,7 +110,15 @@ class SystemCrypto {
return; return;
} else { } 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(); await this.generateAndGuideDatabaseKey();
} catch (error) { } catch (error) {
@@ -140,7 +156,11 @@ class SystemCrypto {
process.env.INTERNAL_AUTH_TOKEN = tokenMatch[1]; process.env.INTERNAL_AUTH_TOKEN = tokenMatch[1];
return; return;
} }
} catch {} } catch (error) {
databaseLogger.debug("Operation failed, continuing", {
error: error instanceof Error ? error.message : String(error),
});
}
await this.generateAndGuideInternalAuthToken(); await this.generateAndGuideInternalAuthToken();
} catch (error) { } catch (error) {

View File

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

View File

@@ -167,7 +167,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders); setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations); setSshConfigurations(uniqueConfigurations);
} catch {} } catch (error) {
console.error("Host manager operation failed:", error);
}
}; };
fetchData(); fetchData();
@@ -196,7 +198,9 @@ export function HostManagerEditor({
setFolders(uniqueFolders); setFolders(uniqueFolders);
setSshConfigurations(uniqueConfigurations); setSshConfigurations(uniqueConfigurations);
} catch {} } catch (error) {
console.error("Host manager operation failed:", error);
}
}; };
window.addEventListener("credentials:changed", handleCredentialChange); 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 } terminal as { refresh?: (start: number, end: number) => void }
).refresh(0, terminal.rows - 1); ).refresh(0, terminal.rows - 1);
} }
} catch {} } catch (error) {
console.error("Terminal operation failed:", error);
}
} }
function performFit() { function performFit() {
@@ -331,7 +333,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
scheduleNotify(cols, rows); scheduleNotify(cols, rows);
hardRefresh(); hardRefresh();
} }
} catch {} } catch (error) {
console.error("Terminal operation failed:", error);
}
}, },
refresh: () => hardRefresh(), refresh: () => hardRefresh(),
}), }),
@@ -738,7 +742,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
return; return;
} }
} catch {} } catch (error) {
console.error("Terminal operation failed:", error);
}
const textarea = document.createElement("textarea"); const textarea = document.createElement("textarea");
textarea.value = text; textarea.value = text;
textarea.style.position = "fixed"; textarea.style.position = "fixed";
@@ -758,7 +764,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
if (navigator.clipboard && navigator.clipboard.readText) { if (navigator.clipboard && navigator.clipboard.readText) {
return await navigator.clipboard.readText(); return await navigator.clipboard.readText();
} }
} catch {} } catch (error) {
console.error("Terminal operation failed:", error);
}
return ""; return "";
} }
@@ -855,7 +863,9 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
const pasteText = await readTextFromClipboard(); const pasteText = await readTextFromClipboard();
if (pasteText) terminal.paste(pasteText); if (pasteText) terminal.paste(pasteText);
} }
} catch {} } catch (error) {
console.error("Terminal operation failed:", error);
}
}; };
element?.addEventListener("contextmenu", handleContextMenu); 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); 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 = () => { const handleError = () => {

View File

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

View File

@@ -54,7 +54,9 @@ async function handleLogout() {
}, },
serverOrigin, 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"); store.put({ handle: dirHandle }, "lastSaveDir");
}; };
} }
} catch {} } catch (error) {
console.error("Drag operation failed:", error);
}
}; };
const isFileSystemAPISupported = () => { const isFileSystemAPISupported = () => {

View File

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

View File

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

View File

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