如何在 C# 中處理二維碼錯誤訊息
IronQR 的錯誤處理功能可協助您擷取讀取和寫入失敗,記錄診斷訊息,並從每次掃描中獲得清晰的結果。 如果不添加明確檢查,無論是空結果還是損壞的檔案都不會傳回任何內容,因此您將不知道哪裡出了問題。 透過新增有針對性的異常處理和診斷日誌記錄,您可以將靜默故障轉化為有用的回饋。 本指南說明如何處理空結果、管理寫入時異常以及為批次處理建構結構化日誌包裝器。
快速入門:處理二維碼錯誤在try-catch區塊中包裹QR讀取操作,並記錄檔案和解碼失敗的診斷。
-
1使用 IronQR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
using IronQr; using IronSoftware.Drawing; using System; using System.IO; using System.Linq; 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}"); }Imports IronQr Imports IronSoftware.Drawing Imports System Imports System.IO Imports System.Linq Try Dim input = New QrImageInput(AnyBitmap.FromFile("label.png")) Dim results = New QrReader().Read(input) Console.WriteLine($"Found {results.Count()} QR code(s)") Catch ex As IOException Console.Error.WriteLine($"File error: {ex.Message}") End TryImports IronQr Imports IronSoftware.Drawing Imports System Imports System.IO Imports System.Linq Try Dim input = New QrImageInput(AnyBitmap.FromFile("label.png")) Dim results = New QrReader().Read(input) Console.WriteLine($"Found {results.Count()} QR code(s)") Catch ex As IOException Console.Error.WriteLine($"File error: {ex.Message}") End Try -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronQR,並使用 免費試用
最小工作流程(5 個步驟)
- 下載IronQR C#程式庫以處理QR碼錯誤
- 將QR的讀取/寫入調用包裹在
try-catch塊中 - 捕獲特定故障的
IOException和ArgumentException - 記錄空結果和異常的診斷訊息
- 使用結構化 JSON 日誌記錄實現管道可觀測性
處理讀取錯誤和空結果
不記錄日誌,空結果和損壞的檔案對呼叫者來說看起來是一樣的。 以下範例偵測文件存取失敗,如果掃描未傳回任何結果,則發出警告。
輸入
此二維碼範例輸入已存在於磁碟上。 我們將模擬兩種情況:一種是使用者檢索並解碼文件,另一種是文件路徑不正確。

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}");
}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 ModuleImports 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輸出
![終端輸出顯示[QRCode] https://ironsoftware.com/qr/scan-1成功讀取QR碼](/static-assets/qr/how-to/detailed-error-messages/success-output-qr.webp)
下方的控制台顯示空結果情況下的[WARN]以及缺失檔案的[ERROR],每個都有檔案路徑和建議的操作。

處理寫入失敗
將null傳遞給QrWriter.Write會觸發IronQrEncodingException。 超出配置錯誤更正級別容量的數據也會引發錯誤,因為更高的更正級別會減少可用數據容量。
輸入
下面的兩個輸入變量定義了失敗情境:nullContent為null且oversizedContent是一個超過QR最大容量的5,000字元字串。
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");
}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 TryImports 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輸出
控制台會顯示兩種故障情況下的異常類型和訊息。

記錄異常訊息中的輸入長度,以確定該問題是否需要更短的內容或更低的修正等級。 對於使用者輸入,在編碼之前驗證字串長度並檢查空值,以減少異常開銷並改善診斷。
記錄二維碼操作
使用IronQr.Logging.Logger來捕捉內部診斷。 對於每個讀取操作,實作一個輔助程序,以 JSON 格式記錄檔案路徑、結果計數和經過時間,以確保整個批次的輸出清晰明了。
輸入
批次包含來自qr-scans/的四個有效QR碼圖像,以及一個具有無效位元組的第五個檔案scan-05-broken.png。

Scan 1

Scan 2

Scan 3

Scan 4
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
// Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All;
IronQr.Logging.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");using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
// Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All;
IronQr.Logging.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
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All
IronQr.Logging.Logger.LogFilePath = "ironqr-debug.log"
' Reusable wrapper for structured observability
Private Function ReadQrWithDiagnostics(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] = $"{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 resultsAndSuccess = ReadQrWithDiagnostics(file)
Dim results = resultsAndSuccess.Item1
Dim success = resultsAndSuccess.Item2
Dim [error] = resultsAndSuccess.Item3
If success AndAlso results.Any() Then ok += 1 Else fail += 1
Next
Console.WriteLine(vbCrLf & $"Batch complete: {ok} success, {fail} failed/empty out of {files.Length} files")Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All
IronQr.Logging.Logger.LogFilePath = "ironqr-debug.log"
' Reusable wrapper for structured observability
Private Function ReadQrWithDiagnostics(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] = $"{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 resultsAndSuccess = ReadQrWithDiagnostics(file)
Dim results = resultsAndSuccess.Item1
Dim success = resultsAndSuccess.Item2
Dim [error] = resultsAndSuccess.Item3
If success AndAlso results.Any() Then ok += 1 Else fail += 1
Next
Console.WriteLine(vbCrLf & $"Batch complete: {ok} success, {fail} failed/empty out of {files.Length} files")輸出
控制台顯示每個檔案的 JSON 日誌行:四次成功讀取和一個針對損壞檔案的結構化錯誤條目,然後是批次摘要。 IronQr.Logging.Logger同時將內部診斷寫入IronQR-debug.log。您可以在這裡下載完整的調試日誌。

JSON輸出直接供應給日誌聚合工具:將stdout輸入到Fluentd、Datadog或CloudWatch的容器化部署中。 ms字段會顯示延遲的回歸,而調試日誌會捕捉包裹器未處理的內部處理步驟。
延伸閱讀
- 錯誤更正級別:在編碼層次調整QR韌性。
- QR碼讀取指南:全程讀取指南。
- QR碼生成器教程:生成帶有樣式和商標的QR碼。
- QrReader API 參考:方法簽名和說明。
- QrWriter API Reference:所有
Write超載。
查看授權選項以準備投入生產。
點擊此處下載完整的DetailedErrorMessagesTest控制台應用專案。
常見問題
如何使用IronQR處理QR碼讀取錯誤?
要用IronQR處理讀取錯誤,將QR讀取操作包裹在try-catch塊中,並使用診斷日誌記錄檢測的空結果和文件訪問失敗。這可以防止無聲失敗並提供清晰的反饋。
如果在掃描過程中未找到QR碼,我該怎麼辦?
如果未找到QR碼,記錄一個包含文件路徑的警告,建議檢查圖像質量或嘗試不同的掃描。此方法提供可操作的見解而不拋出例外。
在使用IronQR創建QR碼時,我應注意哪些例外?
使用IronQR時,需注意當將空數據傳遞給QrWriter.Write時可能出現的IronQrEncodingException,並處理由於高錯誤校正級別而超出QR容量的數據例外。
IronQR如何處理QR碼寫入失敗?
IronQR對空輸入數據拋出IronQrEncodingException,當數據過大超過指定錯誤校正級別時拋出容量例外。記錄輸入長度並相應調整數據大小或校正級別。
在IronQR中使用結構化JSON日誌有何好處?
結構化JSON日誌有助於捕獲QR碼操作的詳細診斷,包括文件路徑、結果數量、經過時間及任何例外。這些資訊有助於監控批處理並除錯。
如何提高使用IronQR進行QR碼處理時的錯誤檢測?
通過實施記錄功能來提高錯誤檢測,該功能捕捉文件路徑、操作狀態、結果數量和執行時間的詳細信息。這些數據支持更容易的除錯及系統可觀察性。
IronQR的日誌輸出可以整合到日誌聚合工具中嗎?
可以,IronQR的JSON輸出可以直接輸入到如Fluentd、Datadog或CloudWatch等日誌聚合工具中,使其適合於容器化部署並增強監控能力。
IronQR對處理批次QR碼操作有什麼建議?
IronQR建議獨立處理每個文件,記錄每次讀取操作的結果以幫助識別錯誤,並提供一份完整的批次總結,統計成功和失敗。
IronQR如何協助診斷在QR碼掃描過程中的文件級失敗?
IronQR檢測如IOException和FileNotFoundException等文件級失敗,提供描述性錯誤信息,這可以被記錄下來以定位例如文件路徑不正確或文件不可讀的問題。
為什麼將QR讀取/寫入調用包裹在try-catch塊中很重要?
將讀取/寫入操作包裹在try-catch塊中可確保故障不會使應用程序崩潰,允許您優雅地處理例外,記錄必要的診斷信息,引導用戶提供有用的消息。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。