Part 08 Unit 02

錯誤處理與除錯

讓你的腳本更穩定可靠



學習目標

  • 了解常見的 Pandoc 錯誤類型
  • 學會 PowerShell 錯誤處理語法
  • 建立穩健的錯誤處理機制
  • 使用 AI 協助除錯

為什麼需要錯誤處理?


沒有錯誤處理時...

腳本遇到問題就直接停止

使用者看到難懂的錯誤訊息

無法知道哪些檔案成功、哪些失敗


有錯誤處理時...

腳本能優雅地處理問題

清楚的錯誤說明和建議

失敗的跳過,成功的繼續

常見的 Pandoc 錯誤類型


錯誤類型 說明 解決方向
檔案不存在 找不到輸入檔 檢查路徑
格式不支援 不認識的格式 確認格式名稱
編碼錯誤 檔案編碼問題 指定 UTF-8
權限不足 無法寫入檔案 檢查權限

解讀錯誤訊息


範例錯誤

pandoc: input.md: openFile: does not exist (No such file or directory)

訊息拆解

PowerShell Try-Catch 基礎


# 基本語法 try { # 可能出錯的程式碼 pandoc input.md -o output.docx } catch { # 錯誤發生時執行 Write-Host "發生錯誤: $_" -ForegroundColor Red } finally { # 無論成功失敗都會執行 Write-Host "處理完成" }

$_ 是一個特殊變數,包含錯誤訊息

實作:基本錯誤處理


1開啟 Antigravity


2請 AI 幫你加入錯誤處理

請幫我把這個 Pandoc 轉換腳本 加入 try-catch 錯誤處理, 當轉換失敗時顯示友善的錯誤訊息

技巧一:預先檢查檔案


在轉換前先確認檔案存在

# 檢查輸入檔案 if (!(Test-Path $inputFile)) { Write-Host "錯誤: 找不到檔案 $inputFile" -ForegroundColor Red exit 1 } # 檔案存在,繼續處理 pandoc $inputFile -o $outputFile

Test-Path 可以檢查檔案或資料夾是否存在

技巧二:確保輸出目錄存在


# 取得輸出檔案的目錄 $outputDir = Split-Path $outputFile -Parent # 如果目錄不存在,自動建立 if (!(Test-Path $outputDir)) { New-Item -ItemType Directory -Path $outputDir -Force | Out-Null Write-Host "已建立目錄: $outputDir" -ForegroundColor Yellow } # 然後再轉換 pandoc $inputFile -o $outputFile

這樣就不會因為目錄不存在而失敗了!

技巧三:驗證轉換結果


# 執行轉換 pandoc $inputFile -o $outputFile # 檢查輸出檔案是否成功建立 if (Test-Path $outputFile) { $size = (Get-Item $outputFile).Length if ($size -gt 0) { Write-Host "轉換成功: $outputFile ($size bytes)" -ForegroundColor Green } else { Write-Host "警告: 輸出檔案是空的" -ForegroundColor Yellow } } else { Write-Host "錯誤: 轉換失敗,沒有產生輸出檔" -ForegroundColor Red }

技巧四:使用 ErrorAction


控制錯誤行為

# 讓錯誤可以被 catch 捕捉 try { pandoc $inputFile -o $outputFile -ErrorAction Stop } catch { Write-Host "轉換失敗: $($_.Exception.Message)" }

ErrorAction 行為
Stop 停止執行,進入 catch
Continue 顯示錯誤,繼續執行
SilentlyContinue 忽略錯誤,繼續執行

批次處理的錯誤處理


# 統計成功和失敗 $success = 0 $failed = 0 $errors = @() foreach ($file in Get-ChildItem *.md) { try { $output = $file.BaseName + ".docx" pandoc $file.FullName -o $output -ErrorAction Stop $success++ Write-Host "✓ $($file.Name)" -ForegroundColor Green } catch { $failed++ $errors += "$($file.Name): $_" Write-Host "✗ $($file.Name)" -ForegroundColor Red } } Write-Host "`n結果: $success 成功, $failed 失敗"

技巧五:記錄錯誤日誌


# 建立日誌檔 $logFile = "convert-$(Get-Date -Format 'yyyyMMdd-HHmmss').log" function Write-Log { param($Message, $Level = "INFO") $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logEntry = "[$timestamp] [$Level] $Message" # 輸出到螢幕和檔案 Write-Host $logEntry $logEntry | Out-File $logFile -Append } # 使用日誌 Write-Log "開始轉換作業" Write-Log "錯誤: 找不到檔案" "ERROR" Write-Log "轉換完成"

完整錯誤處理腳本

# robust-convert.ps1 param( [Parameter(Mandatory=$true)] [string]$InputFile, [string]$OutputFormat = "docx" ) # 步驟 1: 檢查輸入 if (!(Test-Path $InputFile)) { Write-Host "錯誤: 檔案不存在 - $InputFile" -ForegroundColor Red exit 1 } # 步驟 2: 準備輸出 $outputFile = [System.IO.Path]::ChangeExtension($InputFile, $OutputFormat) # 步驟 3: 執行轉換 try { $result = pandoc $InputFile -o $outputFile 2>&1 if (Test-Path $outputFile) { Write-Host "成功: $outputFile" -ForegroundColor Green } else { throw "轉換失敗: 沒有產生輸出檔" } } catch { Write-Host "錯誤: $_" -ForegroundColor Red exit 1 }

使用 AI 協助除錯


在 Antigravity 中提問

我的 Pandoc 腳本出現這個錯誤: pandoc: Could not parse YAML header 請問這是什麼問題?要怎麼修復?

提供的資訊越完整,AI 越能幫你:

  • 完整的錯誤訊息
  • 你執行的指令
  • 輸入檔案的相關內容

常見錯誤與解決方案


錯誤 1: YAML 解析錯誤

Could not parse YAML header

解決:檢查 YAML 開頭結尾的 --- 是否正確,縮排是否一致


錯誤 2: 編碼問題

invalid byte sequence

解決:將檔案轉存為 UTF-8 編碼

更多常見錯誤


錯誤 3: 找不到 LaTeX

pdflatex not found

解決:安裝 MiKTeX 或 TeX Live,或改用其他 PDF 引擎


錯誤 4: 圖片路徑問題

Could not find image

解決:確認圖片路徑正確,使用相對路徑或絕對路徑

除錯技巧


1. 使用 --verbose 查看詳細資訊

pandoc input.md -o output.docx --verbose

2. 分步驟測試

# 先測試基本轉換 pandoc input.md -o test.html # 成功後再加選項 pandoc input.md -o test.docx --reference-doc=template.docx

除錯輔助腳本

# debug-pandoc.ps1 param([string]$InputFile) Write-Host "=== Pandoc 除錯工具 ===" -ForegroundColor Cyan # 檢查檔案 Write-Host "`n1. 檔案資訊:" if (Test-Path $InputFile) { $file = Get-Item $InputFile Write-Host " 大小: $($file.Length) bytes" Write-Host " 修改時間: $($file.LastWriteTime)" } else { Write-Host " 錯誤: 檔案不存在" -ForegroundColor Red exit } # 檢查編碼 Write-Host "`n2. 檔案開頭:" Get-Content $InputFile -TotalCount 5 | ForEach-Object { Write-Host " $_" } # 測試轉換 Write-Host "`n3. 測試轉換:" pandoc $InputFile -o test-output.html --verbose 2>&1

實作練習


任務:建立穩健的轉換腳本


1建立一個新的 PowerShell 腳本


2加入檔案存在檢查


3使用 try-catch 處理轉換錯誤


4加入錯誤日誌功能


5測試各種錯誤情況

錯誤處理最佳實踐


必做清單

  1. 預先檢查 - 在執行前驗證輸入
  2. 友善訊息 - 錯誤訊息要讓人看得懂
  3. 記錄日誌 - 方便事後追查
  4. 優雅降級 - 能繼續的就繼續
  5. 清理資源 - 失敗時刪除不完整的檔案

小測驗


在 PowerShell 中,哪個關鍵字用來捕捉錯誤?



本單元總結


學到的技巧

  • 使用 Try-Catch-Finally 處理錯誤
  • 預先檢查檔案和目錄
  • 驗證轉換結果
  • 記錄錯誤日誌
  • 用 AI 協助分析和修復錯誤

下一步:在 Unit 03 學習工作流程整合