JScript尝试捕获网络异常

时间:2013-06-10 08:50:51

标签: javascript exception networking try-catch jscript

我正在编写一个将数据库备份文件存储到多个位置的脚本。此外,数据存储在通常可访问的NAS上。如果不是这种情况,则会截获错误消息。 我这样试过:

wshshell = WScript.CreateObject("WScript.Shell");
fso = WScript.CreateObject("Scripting.FileSystemObject");

SetupPath = WScript.arguments(0);
if (fso.FileExists(SetupPath))
{
    //Load setup JSON
    SetupFile = fso.OpenTextFile(SetupPath, 1, true, 0);
    eval(SetupFile.ReadAll());

    // Parse setup configuration from JSON
    ...
    BackupPath = Setup["BackupPath"];
    FilesForBackup = Setup["FilesForBackup"];
    NASBackupPath = Setup["NASBackupPath"];
    ...

    CreateNewBackupFiles();

    Log("Script was successfully executed.");
}
else
{
    Log("Script was not successfully executed.");
}

/* Creates a new compressed database backup */
function CreateNewBackupFiles()
{
    tempfile = fso.GetTempName();

    file = fso.GetFile("C:\\Program\\7-Zip\\7z.exe");
    rarexe = file.ShortPath;

    script = rarexe + " a -r " + tempfile + " " + FilesForBackup;
    wshshell.Run(script, 0, true);

    fso.CopyFile(tempfile, BackupPath + PrefixBackupFile + "backup.7z");

    //Save to NAS
    if(NASBackupPath!="")
    {
            try
            {
                    fso.CopyFile(tempfile, NASBackupPath);
            }
            catch(err)
            {
                    Log("Path \"" + NASBackupPath + "\" not available.");
            }
    }
    fso.DeleteFile(tempfile, true); //delete tempfile
}

/* Saves a log in  "Debug.Log" */
function Log(msg)
{
    fs = WScript.CreateObject("Scripting.FileSystemObject");
    a = fs.OpenTextFile("Debug.log", 8, true, 0);
    line = "[" + CurrentTime()+ "] ";
    line += "[" + WScript.ScriptName + "] ";
    line += "[" + msg + "]";
    a.WriteLine(line);  
}

尽管如此,仍然会发出错误。我在Windows XP SP3上使用脚本。是否有可能用javascript捕获此错误?

感谢

1 个答案:

答案 0 :(得分:0)

我发现了错误。错误来自“日志”。首先,并非每次都必须创建新的“文件系统对象”。它可以简单地用于对象“fso”。此外,必须在函数末尾关闭打开的文本文件。这是更正:

function Log(msg)
{
    a = fso.OpenTextFile("Debug.log", 8, true, 0);
    line = "[" + CurrentTime()+ "] ";
    line += "[" + WScript.ScriptName + "] ";
    line += "[" + msg + "]";
    a.WriteLine(line);  
    a.Close();
}