如何在 C# 中處理 QR 碼錯誤訊息
IronQR 的錯誤處理功能可協助您偵測讀寫失敗、記錄診斷資訊,並從每次掃描中獲得清晰的結果。 若未添加明確的檢查機制,無論是空結果還是損壞的檔案,都會返回空值,因此您將無法得知問題出在哪裡。 透過加入針對性的例外處理與診斷記錄,您可以將無聲的失敗轉化為有用的回饋。 本指南說明如何處理空結果、管理寫入時異常,以及為批次處理建立結構化記錄封裝程式。
快速入門:處理 QR 碼錯誤
請將 QR 碼讀取操作封裝在 try-catch 區塊中,並針對檔案讀取及解碼失敗的情況記錄診斷資訊。
-
using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronQR
PM > Install-Package IronQR -
請複製並執行此程式碼片段。
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}"); } -
部署至您的生產環境進行測試
立即透過免費試用,在您的專案中開始使用 IronQR
簡化工作流程(5 個步驟)
- 下載 IronQR C# 程式庫以處理 QR 碼錯誤
- 將 QR 讀寫呼叫封裝在
try-catch區塊中 - 針對特定錯誤,請擷取
IOException和ArgumentException - 針對無結果及異常情況記錄診斷資訊
- 使用結構化 JSON 日誌來提升管道可觀察性
處理讀取錯誤與空結果
若未啟用記錄功能,對呼叫方而言,空結果與損壞的檔案看起來並無二致。 以下範例會偵測檔案存取失敗的情況,並在掃描未返回任何結果時發出警告。
輸入
此 QR 範例輸入檔已存在於磁碟中。 我們將模擬兩種情境:一種是使用者成功取得並解碼檔案,另一種則是檔案路徑不正確的情況。
: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
輸出
下方的控制台顯示,當結果為空時會出現 [WARN],檔案遺失時則顯示 [ERROR],並分別附上檔案路徑及建議的處理方式。
處理寫入失敗
將 null 傳遞給 QrWriter.Write 會觸發 IronQrEncodingException。 超過設定錯誤修正等級容量的資料也會觸發錯誤,因為較高的修正等級會減少可用資料容量。
輸入
以下兩個輸入變數定義了錯誤情境:nullContent 為 null,而 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
輸出
控制台會顯示兩種失敗情境的例外類型與訊息。
請在例外訊息中記錄輸入長度,以判斷問題是需要縮短內容,還是降低修正等級。 針對使用者輸入,請在編碼前驗證字串長度並檢查空值,以減少例外狀況的開銷並改善診斷能力。
記錄 QR 碼操作
請使用 IronSoftware.Logger 來捕捉內部診斷訊息。 針對每次讀取操作,請實作一個輔助程式,將檔案路徑、結果數量及耗時以 JSON 格式記錄下來,以確保整個批次處理的輸出結果清晰明確。
輸入
此批次包含來自 qr-scans/ 的四個有效 QR 碼圖像,以及第五個檔案 scan-05-broken.png,該檔案含有無效位元組。
掃描 1
掃描 2
掃描 3
掃描 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")
輸出
控制台會針對每個檔案顯示 JSON 日誌行:四個成功讀取的記錄,以及一個針對損壞檔案的結構化錯誤條目,隨後是批次摘要。 IronSoftware.Logger 同時將內部診斷資訊寫入 IronQR-debug.log。您可在此處下載完整的除錯日誌。
生成的 JSON 輸出可直接饋送至日誌彙總工具:在容器化部署環境中,將 stdout 透過管道傳送至 Fluentd、Datadog 或 CloudWatch。 ms 欄位會顯示延遲退化問題,而除錯日誌則記錄了封裝程式未記錄的內部處理步驟。
延伸閱讀
- 錯誤糾正等級:在編碼層級調整 QR 碼的抗干擾能力。
- 掃描 QR 碼教學:端到端掃描操作指南。
- QR 碼生成器教學:帶有樣式與標誌的生成方法。
- QrReader API 參考手冊:方法簽名與說明。
- QrWriter API 參考手冊:所有
Write重載方法。
當您準備投入生產環境時,請查看授權選項。
點擊此處下載完整的 DetailedErrorMessagesTest 控制台應用程式專案。
常見問題
如何在 C# 中除錯 QR 碼的讀寫操作?
您可以透過 IronQR 在 C# 中除錯 QR 碼讀寫操作,方法包括擷取例外狀況、記錄診斷資訊,以及透過結構化輸出監控批次處理。
若在 C# 中處理 QR 碼時遇到錯誤,該怎麼辦?
若您在使用 C# 處理 QR 碼時遇到錯誤,請使用 IronQR 來擷取並處理例外狀況。這將有助於您有效識別並解決問題。
IronQR 如何協助監控 QR 碼批次處理?
IronQR 透過提供結構化輸出,協助監控 QR 碼批次處理流程,有助於識別並解決處理過程中可能出現的任何錯誤或效率問題。
IronQR 能否記錄 QR 碼操作的診斷資訊?
是的,IronQR 能針對 QR 碼操作記錄診斷資訊,讓您追蹤並分析 C# 應用程式的效能與錯誤。
using IronQR 處理 QR 碼時,常見的例外情況有哪些?
using IronQR 處理 QR 碼時常見的例外情況,包括 QR 碼無法讀取及格式處理錯誤等問題,可透過 C# 程式碼中的適當例外處理機制來處理。

