C# ile QR Kodu Hata Mesajları Nasıl Yönlendirilir

This article was translated from English: Does it need improvement?
Translated
View the article in English

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.

  1. NuGet Paket Yöneticisi ile https://www.nuget.org/packages/IronQR yükleyin

    PM > Install-Package IronQR
  2. 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}");
    }
  3. Canlı ortamınızda test etmek için dağıtın

    Bugün projenizde IronQR kullanmaya başlayın ücretsiz deneme ile

    arrow pointer

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ış.

Gecerli QR kodu girdi https://ironsoftware.com/qr/scan-1
: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
$vbLabelText   $csharpLabel

Çıktı

Terminal çıktısı [QRCode] https://ironsoftware.com/qr/scan-1 olarak başarılı bir QR kodu okuma için gösterilmektedir

Lütfen dikkate alinBasarili bir okuma sadece QR kodu degerini dondurürken, runtime sirasinda bir hata gecersizlik mesaji veya aşağıda gösterilen uyarilari gösterir.

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.

damaged-scan.png'de QR kodları bulunamadı ve missing-label.png için dosya bulunamadı ibaresini gösteren terminal çıktısı

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
$vbLabelText   $csharpLabel

Çıktı

Konsol, her iki hata senaryosu için istisna tipini ve mesajını gösterir.

Terminal çıktısı, QrWriter.Write için geçersiz null içerik geçirildiğinde IronQrEncodingException'ı 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.

QR code encoding https://ironsoftware.com/qr/scan-1
QR code encoding https://ironsoftware.com/qr/scan-2
QR code encoding https://ironsoftware.com/qr/scan-3
QR code encoding https://ironsoftware.com/qr/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")
$vbLabelText   $csharpLabel

Çı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.

Konsol çıktısı, 4 başarılı okuma ve bir hata için yapılı JSON kayıt satırlarını ve toplu iş bitim özetini gösterir

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

Üretime hazır olduğunuzda lisanslama seçeneklerini görüntüleyin

İndirmek için tıklayın DetaylıHataMesajlarıTesti konsol uygulama projesi

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 64,787 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package IronQR
bir örneği çalıştır URL'inin bir QR koduna dönüşünü izle.