如何在 C# 中处理二维码错误信息
IronQR 的错误处理功能可帮助您捕获读取和写入失败,记录诊断信息,并从每次扫描中获得清晰的结果。 如果不添加显式检查,无论是空结果还是损坏的文件都不会返回任何内容,因此您将不知道哪里出了问题。 通过添加有针对性的异常处理和诊断日志记录,您可以将静默故障转化为有用的反馈。 本指南解释了如何处理空结果、管理写入时异常以及为批量处理构建结构化日志包装器。
快速入门:处理二维码错误将QR读取操作包装在try-catch块中,并记录文件和解码失败的诊断信息。
-
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码生成器教程:带有样式和徽标的生成。
- QrReader API参考:方法签名和备注。
- QrWriter API参考:所有
Write重载。
查看许可选项以准备生产。
点击这里下载完整的DetailedErrorMessagesTest控制台应用程序项目。
常见问题
如何使用IronQR处理二维码读取错误?
要使用IronQR处理读取错误,请将二维码读取操作放在try-catch块中,并使用诊断日志记录来检测空结果和文件访问失败。这可以防止静默失败并提供清晰的反馈,以指明问题所在。
扫描期间未找到二维码时,我应该做什么?
如果未找到二维码,记录一个警告,包含文件路径,并建议检查图像质量或尝试其他扫描。此方法提供可操作的见解而无需抛出异常。
使用IronQR创建二维码时,我应该注意哪些异常?
使用IronQR时,注意在将空数据传递给QrWriter.Write时会出现的IronQrEncodingException,并处理因高错误校正级别导致数据超出二维码容量的异常。
IronQR如何处理二维码写入失败?
对于空输入数据,IronQR抛出IronQrEncodingException,对于容量超出的异常,在数据过大以至于指定的错误校正级别时也是这样。记录输入长度并相应调整数据大小或校正级别。
在IronQR中进行结构化JSON日志记录有什么好处?
结构化JSON日志记录有助于捕获二维码操作的详细诊断信息,包括文件路径、结果计数、经过时间和任何异常。这些信息对于监控批处理过程和调试非常有用。
如何使用IronQR提高二维码处理中的错误检测?
通过实现日志记录来提高错误检测,该日志记录能够捕获有关文件路径、操作状态、结果计数和执行时间的详细信息。这些数据支持更轻松的调试和系统可观测性。
IronQR的日志输出可以与日志聚合工具集成吗?
可以,来自IronQR的JSON输出可以直接传输到诸如Fluentd、Datadog或CloudWatch之类的日志聚合工具中,使其适合于容器化部署并增强监控能力。
IronQR建议如何处理批量二维码操作?
IronQR建议单独处理每个文件,记录每次读取操作的结果,以帮助识别错误,并提供一个完整的批量总结,统计成功和失败的次数。
IronQR如何协助诊断二维码扫描期间的文件级别故障?
IronQR检测文件级故障,如IOException和FileNotFoundException,提供描述性错误信息,可以记录下来以定位诸如文件路径错误或文件无法读取的问题。
为什么在try-catch块中包装二维码读写调用很重要?
将读写操作包装在try-catch块中可以确保故障不会导致应用程序崩溃,从而允许您优雅地处理异常,记录必要的诊断信息,并通过有用的信息引导用户。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。