How to Handle QR Code Error Messages in C#
IronQR's error handling helps you catch read and write failures, log diagnostics, and get clear results from every scan. If you do not add explicit checks, both an empty result and a corrupted file will return nothing, so you will not know what went wrong. By adding targeted exception handling and diagnostic logging, you can turn silent failures into useful feedback. This guide explains how to handle empty results, manage write-time exceptions, and build a structured logging wrapper for batch processing.
Quickstart: Handle QR Code Errors
Wrap QR read operations in a try-catch block and log diagnostics for file and decode failures.
-
Install IronQR with NuGet Package Manager
PM > Install-Package IronQR -
Copy and run this code snippet.
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}"); } -
Deploy to test on your live environment
Start using IronQR in your project today with a free trial
Minimal Workflow (5 steps)
- Download the IronQR C# library for QR code error handling
- Wrap QR read/write calls in try-catch blocks
- Catch
IOExceptionandArgumentExceptionfor specific failures - Log diagnostics for empty results and exceptions
- Use structured JSON logging for pipeline observability
Handling Read Errors and Empty Results
Without logging, an empty result and a corrupted file appear identical to the caller. The following example detects file access failures and issues a warning if the scan returns no results.
Input
This QR example input exists on disk. We will simulate both scenarios: one where the user retrieves and decodes the file, and another where the file path is incorrect.
: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
Output
The console below shows a [WARN] for the empty-result case and an [ERROR] for the missing file, with the file path and a suggested action for each.
Handling Write Failures
Passing null to QrWriter.Write triggers an IronQrEncodingException. Data that exceeds capacity for the configured error correction level also throws, since higher correction levels reduce available data capacity.
Input
The two input variables below define the failure scenarios: nullContent is null and oversizedContent is a 5,000-character string that exceeds QR capacity at the highest correction level.
: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
Output
The console shows the exception type and message for both failure scenarios.
Log the input length with the exception message to identify whether the issue requires shorter content or a lower correction level. For user input, validate string length and check for null values before encoding to reduce exception overhead and improve diagnostics.
Logging QR Code Operations
Use IronSoftware.Logger to capture internal diagnostics. For each read operation, implement a helper that logs the file path, result count, and elapsed time as JSON to ensure clear output for the entire batch.
Input
The batch includes four valid QR code images from qr-scans/ and a fifth file, scan-05-broken.png, with invalid bytes.
Scan 1
Scan 2
Scan 3
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")
Output
The console shows JSON log lines for each file: four successful reads and one structured error entry for the broken file, followed by the batch summary. IronSoftware.Logger writes internal diagnostics to IronQR-debug.log at the same time. You can download the full debug log here.
The JSON output feeds directly into log aggregation tools: pipe stdout to Fluentd, Datadog, or CloudWatch in a containerized deployment. The ms field surfaces latency regressions, and the debug log captures internal processing steps that the wrapper does not.
Further Reading
- Error Correction Levels: tune QR resilience at the encoding level.
- Reading QR Codes How-To: end-to-end reading walkthrough.
- QR Code Generator Tutorial: generation with styling and logos.
- QrReader API Reference: method signatures and remarks.
- QrWriter API Reference: all Write overloads.
View licensing options when you're ready for production.
Click here to download the complete DetailedErrorMessagesTest console app project.

