QR 코드 작업 디버깅 및 C#의 오류 메시지 처리 방법

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

수백 개의 이미지를 시간당 처리하는 QR 코드 파이프라인은 구조화된 오류 처리가 필요합니다 — 단순히 try-catch만이 아닌, 어떤 파일이 실패했는지, 입력이 어떤 모양이었는지, 그리고 실패 원인이 손상된 이미지인지 용량 제한인지 누락된 종속성인지 등을 즉시 알려주는 진단 출력을 제공해야 합니다. 로그 없이 "QR 찾지 못함"과 "입력이 유효하지 않음"을 구별할 수 없는 상황에서 조용한 빈 결과는 처리되지 않은 예외만큼 위험합니다.

IronQR는 읽기를 위한 QrReader와 생성을 위한 QrWriter을 제공합니다. IronBarcode와 달리, IronQR는 사용자 정의 예외 계층을 정의하지 않습니다. 작업은 표준 .NET 예외 (ArgumentNullException, ArgumentException, IOException)를 던지며, 이는 BCL 타입을 중심으로 catch 블록을 구조화하고 우리가 제어하는 컨텍스트에서 진단 정보를 추출함을 의미합니다. 아래에서 읽기 시 오류, 기록 시 오류 및 재사용 가능한 로깅 래퍼를 다룹니다.

빠른 시작: 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 코드 읽기에서 상세한 오류 메시지를 얻는 방법은?

우리는 AnyBitmap.FromFile() (파일 접근)과 QrReader.Read() (디코드)에서 발생하는 예외를 catch하고, 빈 결과 케이스를 별도로 검사하여 읽기 실패를 처리합니다. QR 코드를 찾지 못한 읽기는 던지지 않고 비어있는 IEnumerable<QrResult>를 반환합니다. 이는 오류가 아닌 예상된 동작이지만, 여전히 생산 파이프라인에서 진단 이벤트로 기록되어야 합니다.

: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}");
}
$vbLabelText   $csharpLabel

QrResult 객체는 세 가지 진단 필드를 노출합니다: Value (디코딩된 문자열), Points (감지된 QR 영역의 네 모서리 좌표), 그리고 QrType (QRCode, MicroQRCode, 또는 RMQRCode 중 하나). 읽기가 부분적이거나 예상 외의 결과를 생성할 때, QrType 필드는 스캐너가 표준 QR인지 변형 형식을 감지했는지 여부를 확인하는 데 도움이 됩니다.


QR 코드 생성 실패를 디버그하는 방법?

QrWriter.Write()는 입력이 QR 인코딩 제약 조건을 위반했을 때 던집니다. null을 넘기면 ArgumentNullException가 발생합니다. 선택된 오류 수정 수준에 대한 최대 용량을 초과하는 데이터는 ArgumentException를 던집니다. 더 높은 수정 수준 (예: QrErrorCorrectionLevel.Highest)은 사용 가능한 데이터 용량을 줄이므로 같은 문자열이 Medium에서는 성공할 수 있지만 Highest에서는 실패할 수 있습니다.

:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/write-diagnostics.cs
using IronQr;

string? content = null;
string oversizedContent = new string('A', 5000);

// Scenario 1: null input
try
{
    QrCode qr = QrWriter.Write(content);
}
catch (ArgumentNullException ex)
{
    Console.Error.WriteLine($"[ERROR] Null content: {ex.ParamName} — {ex.Message}");
}

// 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);
}
catch (ArgumentException ex)
{
    Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}");
    Console.Error.WriteLine($"  Input length: {oversizedContent.Length} chars");
    Console.Error.WriteLine($"  Action: Reduce content or lower error correction level");
}
$vbLabelText   $csharpLabel

우리는 예외 메시지와 함께 입력 길이를 기록하여 긴급 엔지니어에게 해결책이 더 짧은 콘텐츠인지, 더 낮은 오류 수정 레벨인지 판단할 수 있는 충분한 컨텍스트를 제공합니다. 오류 수정 기사는 용량 절충에 대해 자세히 설명합니다. 여기에서는 그 내용을 복제하는 대신 링크를 겁니다.

사용자 제공 콘텐츠를 허용하는 생성 워크플로의 경우, QrWriter.Write()를 호출하기 전에 문자열 길이 및 널 검사를 검증하는 것이 좋습니다. 사전 검증은 예외 처리를 하는 것보다 저렴하고 명확한 진단 메시지를 생성합니다.


QR 코드 작업을 기록하고 모니터링하는 방법?

IronQR은 제품별 로깅 API를 노출하지 않습니다. Iron Software의 모든 제품에 걸쳐 제공되는 공유 IronSoftware.Logger 클래스는 활성화되면 내부 진단 출력을 포착합니다. 구조적 관찰성을 위해 우리는 QR 작업을 입력 경로, 결과 수, 경과 시간 및 모든 예외를 기계 해독 가능한 아웃풋으로 기록하는 헬퍼 메서드로 포장합니다.

: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");
$vbLabelText   $csharpLabel

JSON 출력은 로그 집계 파이프라인과 직접 통합됩니다 — stdout컨테이너화된 배포에서 Fluentd, Datadog, 또는 CloudWatch로 파이프됩니다. ms 필드는 지연 회귀를 표면화합니다. IronSoftware.Logger 파일은 래퍼가 하지 않는 내부 처리 세부 정보를 캡처합니다. 구조화된 로그만으로 실패를 설명할 수 없는 경우 지원 문제 분석을 위해 유용합니다.

인코딩 수준의 신뢰성을 위해, 오류 수정 방법 가이드는 손상되거나 부분적으로 가려진 코드를 위한 스캔 내성을 개선하기 위해 QrErrorCorrectionLevel을 조정하는 방법을 다룹니다. 오류 수정을 조정하는 것은 보완 전략입니다. 이는 처음에 오류 처리 계층에 도달하는 읽기 실패 수를 줄입니다.


내 다음 단계는 무엇인가요?

우리는 빈 결과 진단이 있는 읽기 시간 오류 처리, 널 및 용량 위반에 대한 쓰기 시간 실패 패턴, 파이프라인 관찰성을 위한 구조화된 JSON 출력을 생성하는 재사용 가능한 로깅 래퍼를 다루었습니다.

추가 읽기 자료:

라이선스 옵션 보기 when the pipeline is ready for production.

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 다운로드 61,359 | 버전: 2026.3 방금 출시되었습니다
Still Scrolling Icon

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

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