C# ile QR Kodu Hata Mesajları Nasıl Yönlendirilir
IronQR'un hata yönetimi, okuma ve yazma hatalarını yakalamanıza, tanısal kayıtlar tutmanıza ve her taramadan net sonuç almanıza yardımcı olur. Açık kontrol eklemezseniz, hem boş bir sonuç hem de bozuk bir dosya hiçbir şey döndürmez, bu yüzden sorunun ne olduğunu bilemezsiniz. Hedefli istisna yönetimi ve tanısal kayıtları ekleyerek sessiz hataları faydalı geri bildirimlere dönüştürebilirsiniz. Bu rehber, boş sonuçların nasıl yönetileceğini, yazma anı istisnalarının nasıl yönetileceğini ve toplu işleme için yapılı bir kayıt sarmalayıcının nasıl oluşturulacağını açıklar.
Hızlı Başlatma: QR Kodu Hatalarını Yönlendirme
QR okuma işlemlerini bir try-catch bloğuna sarın ve dosya ve kod çözme hataları için tanısal kayıtlar tutun.
-
NuGet Paket Yöneticisi ile https://www.nuget.org/packages/IronQR yükleyin
PM > Install-Package IronQR -
Bu kod parçasını kopyalayıp çalıştırın.
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}"); } -
Canlı ortamınızda test etmek için dağıtın
Bugün projenizde IronQR kullanmaya başlayın ücretsiz deneme ile
Minimal İş Akışı (5 adımda)
- IronQR C# kütüphanesini QR kodu hata yönetimi için indirin
- QR okuma/yazma çağrı işlemlerini try-catch bloğuna sarın
- Belirli hatalar için
IOExceptionveArgumentExceptiontutun - Boş sonuçlar ve istisnalar için tanısal kayıtlar tutun
- Hat görünürlüğü için yapılı JSON kayıtlama kullanın
Okuma Hatalarını ve Boş Sonuçları Yönlendirme
Kayıt olmadan, boş bir sonuç ve bozuk bir dosya, çağıran kişinin gözüne aynı görünür. Aşağıdaki örnek, dosya erişim hatalarını algılar ve tarama sonuç vermediyse bir uyarı verir.
Girdi
Bu QR örnek girdi diskte mevcuttur. İki senaryoyu da simüle edeceğiz: birinde kullanıcı dosyayı alır ve kodunu çözmüş, diğerinde ise dosya yolu yanlış.
: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
Çıktı
Aşağıdaki konsol, boş-sonuç durumu için bir [WARN] ve eksik dosya için bir [ERROR] göstermektedir, her biri için dosya yolu ve önerilen bir hareketle birlikte.
Yazma Hatalarını Yönlendirme
null'yi QrWriter.Write'ya geçirmek bir IronQrEncodingException tetikler. Aşırı kapasite kullanan veriler, daha yüksek düzeltme seviyeleri mevcut veri kapasitesini azalttığından, hata düzeltme seviyesi için yapılandırıldıklarında istisna fırlatır.
Girdi
Aşağıdaki iki giriş değişkeni başarısızlık senaryolarını tanımlar: nullContent null ve oversizedContent en yüksek düzeltme seviyesinde QR kapasitesini aşan 5.000 karakterlik bir stringdir.
: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
Çıktı
Konsol, her iki hata senaryosu için istisna tipini ve mesajını gösterir.
Sorunun daha kısa içerik veya daha düşük bir düzeltme seviyesi gerektirip gerektirmediğini belirlemek için istisna mesajı ile birlikte giriş uzunluğunu kaydedin. Kullanıcı girdisi için, kodlamadan önce metin uzunluğunu doğrulayın ve null değerlerini kontrol edin; istisna yükünü azaltmak ve tanıyı iyileştirmek için.
QR Kodu İşlemlerini Kayıt Etme
İç teşhisleri yakalamak için IronSoftware.Logger kullanın. Her okuma işlemi için, çalışma dosya yolunu, sonuç sayısını ve geçen zamanı JSON olarak kaydeden bir yardımcı uygulayın; bu şekilde tüm toplu iş için net çıktıyı sağlayın.
Girdi
Topluca, qr-scans/'dan dört geçerli QR kod görüntüsü ve geçersiz baytlara sahip bir beşinci dosya scan-05-broken.png içerir.
Tarama 1
Tarama 2
Tarama 3
Tarama 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")
Çıktı
Konsol, her dosya için JSON kayıt satırlarını gösterir: dört başarılı okuma ve bozuk dosya için bir yapı işlev bozukluğu girişi, ardından toplu iş özetini takip eder. IronSoftware.Logger aynı zamanda iç teşhisleri IronQR-debug.log'ya yazar. Tüm hata ayıklama günlüğünü buradan indirebilirsiniz.
JSON çıktısı doğrudan günlük toplama araçlarına beslenir: stdout'yi bir konteynerli dağıtımda Fluentd, Datadog veya CloudWatch'a yönlendirin. ms alanı gecikme gerilemelerini ortaya çıkarır ve hata ayıklama günlüğü, sarmalayıcının yakalamadığı iç işlem adımlarını kaydeder.
Daha Fazla Okuma
- QR dayanıklılığını kodlama düzeyinde ayarlayın: Hata Düzeltme Seviyeleri
- Baştan sona okuma yürüyüşü: QR Kodları Nasıl Okunur
- Stil ve logolar ile oluşturma: QR Kodu Oluşturucu Tutorial
- QrReader API Referansı: yöntem imzaları ve notlar.
- Tüm Write aşırı yüklemeleri: QrWriter API Referansı
Üretime hazır olduğunuzda lisanslama seçeneklerini görüntüleyin
İndirmek için tıklayın DetaylıHataMesajlarıTesti konsol uygulama projesi

