C#에서 QR 코드 오류 메시지를 처리하는 방법

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

IronQR의 오류 처리 기능은 읽기 및 쓰기 실패를 포착하고, 진단 로그를 기록하며, 모든 스캔에서 명확한 결과를 얻을 수 있도록 도와줍니다. 명시적인 검사를 추가하지 않으면 결과가 비어 있거나 파일이 손상된 경우 모두 아무런 응답을 반환하지 않으므로 무엇이 잘못되었는지 알 수 없습니다. 특정 예외 처리 및 진단 로깅을 추가하면 조용히 발생하는 오류를 유용한 피드백으로 전환할 수 있습니다. 이 가이드에서는 빈 결과를 처리하는 방법, 쓰기 시간 예외를 관리하는 방법, 그리고 일괄 처리를 위한 구조화된 로깅 래퍼를 구축하는 방법을 설명합니다.

빠른 시작: QR 코드 오류 처리

QR 읽기 작업을 try-catch 블록에 감싸고 파일 및 디코딩 실패에 대한 진단을 기록합니다.

  1. NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/IronQR 설치하기

    PM > Install-Package IronQR
  2. 다음 코드 조각을 복사하여 실행하세요.

    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. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    무료 체험판으로 오늘 프로젝트에서 IronQR 사용 시작하기

    arrow pointer

읽기 오류 및 빈 결과 처리

로깅이 없으면 빈 결과와 손상된 파일이 호출자에게는 동일하게 보입니다. 다음 예제는 파일 접근 실패를 감지하고, 검사 결과가 없으면 경고를 표시합니다.

입력

이 QR 코드 예제 입력은 디스크에 있습니다. 우리는 두 가지 시나리오를 모두 시뮬레이션할 것입니다. 하나는 사용자가 파일을 가져와 디코딩하는 경우이고, 다른 하나는 파일 경로가 잘못된 경우입니다.

유효한 QR 코드 입력 인코딩 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

산출

QR 코드 읽기가 성공적으로 완료되었음을 나타내는 터미널 출력에는 [QRCode] https://ironsoftware.com/qr/scan-1이 표시됩니다.

참고해 주세요읽기에 성공하면 QR 코드 값이 반환되고, 런타임 중 오류가 발생하면 아래와 같은 예외 메시지 또는 경고가 표시됩니다.

아래 콘솔에는 결과가 없는 경우 [WARN]가, 파일이 누락된 경우 [ERROR]가 표시되며, 각각에 대한 파일 경로와 권장 조치가 함께 제공됩니다.

터미널 출력에는 damaged-scan.png에서 QR 코드를 찾을 수 없다는 경고 메시지와 missing-label.png에 대한 파일을 찾을 수 없다는 오류가 표시됩니다.

쓰기 오류 처리

nullQrWriter.Write로 전달하면 IronQrEncodingException가 트리거됩니다. 설정된 오류 수정 수준 의 용량을 초과하는 데이터도 오류를 발생시킵니다. 오류 수정 수준이 높을수록 사용 가능한 데이터 용량이 줄어들기 때문입니다.

입력

아래의 두 입력 변수는 오류 시나리오를 정의합니다: nullContentnull이며, oversizedContent은 최고 오류 정정 수준에서 QR 코드 용량을 초과하는 5,000자 길이의 문자열입니다.

: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

산출

콘솔에는 두 가지 오류 시나리오 모두에 대한 예외 유형과 메시지가 표시됩니다.

QrWriter.Write에 null 콘텐츠가 전달되어 IronQrEncodingException이 발생했음을 보여주는 터미널 출력입니다.

입력 길이와 예외 메시지를 기록하여 문제 해결에 더 짧은 콘텐츠가 필요한지 또는 더 낮은 수정 수준이 필요한지 파악합니다. 사용자 입력에 대해 인코딩 전에 문자열 길이를 검증하고 null 값을 확인하여 예외 발생률을 줄이고 진단 기능을 향상시키십시오.


QR 코드 작업 로깅

내부 진단 정보를 캡처하려면 IronSoftware.Logger을 사용하십시오. 각 읽기 작업에 대해 파일 경로, 결과 개수 및 경과 시간을 JSON 형식으로 기록하는 헬퍼 함수를 ​​구현하여 전체 배치에 대한 명확한 출력을 보장하십시오.

입력

이 배치에는 qr-scans/의 유효한 QR 코드 이미지 4개와, 무효한 바이트가 포함된 다섯 번째 파일 scan-05-broken.png이 포함되어 있습니다.

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

산출

콘솔에는 각 파일에 대한 JSON 로그 라인이 표시됩니다. 성공적인 읽기 4건과 손상된 파일에 대한 구조화된 오류 항목 1건, 그리고 배치 요약이 표시됩니다. IronSoftware.Logger은 동시에 IronQR-debug.log에 내부 진단 정보를 기록합니다. 전체 디버그 로그는 여기에서 다운로드할 수 있습니다.

터미널 출력에는 4건의 성공적인 읽기 작업과 1건의 오류에 대한 JSON 구조의 로그 라인 Plus 배치 완료 요약이 표시됩니다.

생성된 JSON 출력은 로그 집계 도구로 직접 전송됩니다: 컨테이너화된 배포 환경에서 stdout을 Fluentd, Datadog 또는 CloudWatch로 파이프라인으로 전송합니다. ms 필드는 지연 시간 저하 현상을 표시하며, 디버그 로그는 래퍼가 기록하지 않는 내부 처리 단계를 캡처합니다.


추가 자료

제품 출시 준비가 완료되면 라이선스 옵션을 확인하세요 .

여기를 클릭하여 DetailedErrorMessagesTest 콘솔 앱 프로젝트 전체를 다운로드하세요 .

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

시작할 준비 되셨나요?
Nuget 다운로드 63,625 | 버전: 2026.4 방금 출시되었습니다
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package IronQR
샘플을 실행하세요 URL이 QR 코드로 바뀌는 것을 확인해 보세요.