如何在 C# 中處理二維碼錯誤訊息

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronQR 的錯誤處理功能可協助您擷取讀取和寫入失敗,記錄診斷訊息,並從每次掃描中獲得清晰的結果。 如果不添加明確檢查,無論是空結果還是損壞的檔案都不會傳回任何內容,因此您將不知道哪裡出了問題。 透過新增有針對性的異常處理和診斷日誌記錄,您可以將靜默故障轉化為有用的回饋。 本指南說明如何處理空結果、管理寫入時異常以及為批次處理建構結構化日誌包裝器。

快速入門:處理二維碼錯誤

將 QR 讀取操作封裝在 try-catch 區塊中,並記錄檔案和解碼失敗的診斷資訊。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronQR

    PM > Install-Package IronQR
  2. 複製並運行這段程式碼。

    using IronQr;
    using IronSoftware.Drawing;
    
    try
    {
        var input = new QrImageInput(AnyBitmap.FromFile("label.png"));
        var results = new QrReader().Read(input);
        Console.WriteLine($"Found {results.Count()} QR code(s)");
    }
    catch (IOException ex)
    {
        Console.Error.WriteLine($"File error: {ex.Message}");
    }
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronQR

    arrow pointer

處理讀取錯誤和空結果

不記錄日誌,空結果和損壞的檔案對呼叫者來說看起來是一樣的。 以下範例偵測文件存取失敗,如果掃描未傳回任何結果,則發出警告。

輸入

此二維碼範例輸入已存在於磁碟上。 我們將模擬兩種情況:一種是使用者檢索並解碼文件,另一種是文件路徑不正確。

有效的二維碼輸入編碼 https://ironsoftware.com/qr/scan-1
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/read-diagnostics.cs
using IronQr;
using IronSoftware.Drawing;

string filePath = "damaged-scan.png";

try
{
    // File-level failure throws IOException or FileNotFoundException
    var inputBmp = AnyBitmap.FromFile(filePath);
    var imageInput = new QrImageInput(inputBmp);

    var reader = new QrReader();
    IEnumerable<QrResult> results = reader.Read(imageInput);

    if (!results.Any())
    {
        // Not an exception — but a diagnostic event worth logging
        Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}");
        Console.Error.WriteLine($"  Action: Verify image quality or try a different scan");
    }
    else
    {
        foreach (QrResult result in results)
        {
            Console.WriteLine($"[{result.QrType}] {result.Value}");
        }
    }
}
catch (FileNotFoundException)
{
    Console.Error.WriteLine($"[ERROR] File not found: {filePath}");
}
catch (IOException ex)
{
    Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}");
}
catch (Exception ex)
{
    Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}");
}
Imports IronQr
Imports IronSoftware.Drawing

Module Module1
    Sub Main()
        Dim filePath As String = "damaged-scan.png"

        Try
            ' File-level failure throws IOException or FileNotFoundException
            Dim inputBmp = AnyBitmap.FromFile(filePath)
            Dim imageInput = New QrImageInput(inputBmp)

            Dim reader = New QrReader()
            Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

            If Not results.Any() Then
                ' Not an exception — but a diagnostic event worth logging
                Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}")
                Console.Error.WriteLine("  Action: Verify image quality or try a different scan")
            Else
                For Each result As QrResult In results
                    Console.WriteLine($"[{result.QrType}] {result.Value}")
                Next
            End If
        Catch ex As FileNotFoundException
            Console.Error.WriteLine($"[ERROR] File not found: {filePath}")
        Catch ex As IOException
            Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}")
        Catch ex As Exception
            Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}")
        End Try
    End Sub
End Module
$vbLabelText   $csharpLabel

輸出

終端輸出顯示 [QRCode] https://ironsoftware.com/qr/scan-1,表示二維碼讀取成功

請注意成功讀取時只會傳回二維碼值,而執行時出錯則會顯示如下所示的異常訊息或警告。

下方的控制台顯示,當結果為空時會出現 [WARN],檔案遺失時則顯示 [ERROR],並分別附上檔案路徑及建議的處理方式。

終端輸出顯示警告訊息:未在 damage-scan.png 中找到二維碼;錯誤訊息:未找到 missing-label.png 檔案。

處理寫入失敗

null 傳遞給 QrWriter.Write 會觸發 IronQrEncodingException。 超出配置糾錯等級的資料容量也會拋出異常,因為更高的糾錯等級會降低可用資料容量。

輸入

以下兩個輸入變數定義了失敗情境:nullContentnull,而 oversizedContent 則是一串長達 5,000 字元的字串,其長度已超出 QR 碼在最高修正等級下的容量。

:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/write-diagnostics.cs
using IronQr;

string? content = null; // null throws IronQrEncodingException 
string oversizedContent = new string('A', 5000); // 5,000 chars exceeds QR capacity at Highest error correction level 

// Scenario 1: null input
try
{   
    QrCode qr = QrWriter.Write(content); // Input
}
catch (Exception ex)
{
    Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}"); // Output
}

// Scenario 2: data exceeds QR capacity at the configured error correction level
try
{
    var options = new QrOptions(QrErrorCorrectionLevel.Highest);
    QrCode qr = QrWriter.Write(oversizedContent, options); // Input
}
catch (Exception ex)
{
    Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}"); // Output
    Console.Error.WriteLine($"  Input length: {oversizedContent.Length} chars");
    Console.Error.WriteLine($"  Action: Reduce content or lower error correction level");
}
Imports IronQr

Dim content As String = Nothing ' Nothing throws IronQrEncodingException 
Dim oversizedContent As String = New String("A"c, 5000) ' 5,000 chars exceeds QR capacity at Highest error correction level 

' Scenario 1: null input
Try
    Dim qr As QrCode = QrWriter.Write(content) ' Input
Catch ex As Exception
    Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}") ' Output
End Try

' Scenario 2: data exceeds QR capacity at the configured error correction level
Try
    Dim options As New QrOptions(QrErrorCorrectionLevel.Highest)
    Dim qr As QrCode = QrWriter.Write(oversizedContent, options) ' Input
Catch ex As Exception
    Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}") ' Output
    Console.Error.WriteLine($"  Input length: {oversizedContent.Length} chars")
    Console.Error.WriteLine("  Action: Reduce content or lower error correction level")
End Try
$vbLabelText   $csharpLabel

輸出

控制台會顯示兩種故障情況下的異常類型和訊息。

終端輸出顯示 IronQrEncodingException 異常,原因是傳遞給 QrWriter.Write 的內容為空。

記錄異常訊息中的輸入長度,以確定該問題是否需要更短的內容或更低的修正等級。 對於使用者輸入,在編碼之前驗證字串長度並檢查空值,以減少異常開銷並改善診斷。


記錄二維碼操作

請使用 IronSoftware.Logger 來標記內部診斷資訊。 對於每個讀取操作,實作一個輔助程序,以 JSON 格式記錄檔案路徑、結果計數和經過時間,以確保整個批次的輸出清晰明了。

輸入

此批次包含來自 qr-scans/ 的四個有效 QR 碼圖像,以及第五個檔案 scan-05-broken.png,該檔案含有無效位元組。

QR code encoding https://ironsoftware.com/qr/scan-1
QR code encoding https://ironsoftware.com/qr/scan-2
QR code encoding https://ironsoftware.com/qr/scan-3
QR code encoding https://ironsoftware.com/qr/scan-4
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/logging-wrapper.cs
using IronQr;
using IronSoftware.Drawing;
using System.Diagnostics;

// Enable shared Iron Software logging for internal diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironqr-debug.log";

// Reusable wrapper for structured observability
(IEnumerable<QrResult> Results, bool Success, string Error) ReadQrWithDiagnostics(string filePath)
{
    var sw = Stopwatch.StartNew();
    try
    {
        var input = new QrImageInput(AnyBitmap.FromFile(filePath));
        var results = new QrReader().Read(input).ToList();
        sw.Stop();

        Console.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
            + $"\"status\":\"ok\",\"count\":{results.Count},\"ms\":{sw.ElapsedMilliseconds}}}");

        return (results, true, null);
    }
    catch (Exception ex)
    {
        sw.Stop();
        string error = $"{ex.GetType().Name}: {ex.Message}";

        Console.Error.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
            + $"\"status\":\"error\",\"exception\":\"{ex.GetType().Name}\","
            + $"\"message\":\"{ex.Message}\",\"ms\":{sw.ElapsedMilliseconds}}}");

        return (Enumerable.Empty<QrResult>(), false, error);
    }
}

// Usage: process a batch with per-file isolation
string[] files = Directory.GetFiles("qr-scans/", "*.png");
int ok = 0, fail = 0;

foreach (string file in files)
{
    var (results, success, error) = ReadQrWithDiagnostics(file);
    if (success && results.Any()) ok++;
    else fail++;
}

Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files");
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Diagnostics
Imports System.IO
Imports System.Linq

' Enable shared Iron Software logging for internal diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironqr-debug.log"

' Reusable wrapper for structured observability
Private Function ReadQrWithDiagnostics(ByVal filePath As String) As (IEnumerable(Of QrResult), Boolean, String)
    Dim sw = Stopwatch.StartNew()
    Try
        Dim input = New QrImageInput(AnyBitmap.FromFile(filePath))
        Dim results = New QrReader().Read(input).ToList()
        sw.Stop()

        Console.WriteLine($"{{""op"":""qr_read"",""file"":""{Path.GetFileName(filePath)}"",""status"":""ok"",""count"":{results.Count},""ms"":{sw.ElapsedMilliseconds}}}")

        Return (results, True, Nothing)
    Catch ex As Exception
        sw.Stop()
        Dim error As String = $"{ex.GetType().Name}: {ex.Message}"

        Console.Error.WriteLine($"{{""op"":""qr_read"",""file"":""{Path.GetFileName(filePath)}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""ms"":{sw.ElapsedMilliseconds}}}")

        Return (Enumerable.Empty(Of QrResult)(), False, error)
    End Try
End Function

' Usage: process a batch with per-file isolation
Dim files As String() = Directory.GetFiles("qr-scans/", "*.png")
Dim ok As Integer = 0, fail As Integer = 0

For Each file As String In files
    Dim result = ReadQrWithDiagnostics(file)
    Dim results = result.Item1
    Dim success = result.Item2
    Dim error = result.Item3

    If success AndAlso results.Any() Then
        ok += 1
    Else
        fail += 1
    End If
Next

Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files")
$vbLabelText   $csharpLabel

輸出

控制台顯示每個檔案的 JSON 日誌行:四次成功讀取和一個針對損壞檔案的結構化錯誤條目,然後是批次摘要。 IronSoftware.Logger 同時將內部診斷資訊寫入 IronQR-debug.log。您可在此處下載完整的除錯日誌。

終端輸出顯示了 4 次成功讀取和 1 次錯誤的 JSON 結構化日誌行,Plus批次完成摘要。

生成的 JSON 輸出可直接饋送至日誌彙總工具:在容器化部署環境中,透過管道 stdout 將資料傳送至 Fluentd、Datadog 或 CloudWatch。 ms 欄位會顯示延遲退化現象,而除錯日誌則記錄了封裝程式未記錄的內部處理步驟。


延伸閱讀

-糾錯等級:在編碼等級調整 QR 碼的容錯能力。 -如何讀取二維碼:從頭到尾的讀取指南。 -二維碼產生器教學:產生帶有樣式和標誌的二維碼。

準備投入生產時,請查看許可證選項

點擊這裡下載完整的 DetailedErrorMessagesTest 控制台應用程式專案。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 63,625 | 版本: 2026.4 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronQR
執行範例 觀看您的 URL 變成 QR code。