본문으로 건너뛰기
cccskills
무료GitHub에 공개

http-status-aware-error-handling

Graceful HTTP error handling in Web controllers with status-code-specific user messaging

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

실행 점수 미검증

설치 방법 보기

포함된 파일(1)

  • SKILL.md5.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Context

ASP.NET Core Web controllers calling downstream APIs via HttpClient should differentiate HTTP error responses based on status code, providing appropriate user feedback:

  • 4xx client errors: User-actionable messages (validation, conflict, not found)
  • 5xx server errors: Technical error messages with details for support
  • 409 Conflict (idempotency): Warning-level feedback, not error-level

This applies when:

  • Web layer calls API via IDownstreamApi or HttpClient
  • Operations can return 409 Conflict for "already done" scenarios (duplicate resource, idempotent retry)
  • User experience should distinguish between "this is fine" vs "something broke"

Patterns

1. Check HttpRequestException.StatusCode

try
{
    var result = await _service.AddResourceAsync(id, data);
    if (result is null)
    {
        TempData["ErrorMessage"] = "Failed to add resource.";
    }
    else
    {
        TempData["SuccessMessage"] = "Resource added successfully.";
    }
}
catch (HttpRequestException ex)
{
    // Differentiate based on status code
    if (ex.StatusCode == System.Net.HttpStatusCode.Conflict)
    {
        TempData["WarningMessage"] = "This resource is already associated.";
    }
    else if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
    {
        TempData["ErrorMessage"] = "The target resource was not found.";
    }
    else
    {
        TempData["ErrorMessage"] = $"Failed to add resource: {ex.Message}";
    }
}

2. Support TempData Warning Messages in Layout

Ensure _Layout.cshtml (or equivalent) displays warning-level messages:

@if (TempData["SuccessMessage"] != null)
{
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        @TempData["SuccessMessage"]
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
}
@if (TempData["WarningMessage"] != null)
{
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
        @TempData["WarningMessage"]
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
}
@if (TempData["ErrorMessage"] != null)
{
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        @TempData["ErrorMessage"]
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
}

3. Test Both Happy and Error Paths

[Fact]
public async Task Action_When409Conflict_RedirectsWithWarningMessage()
{
    // Arrange
    var conflictException = new HttpRequestException(
        "Conflict",
        null,
        System.Net.HttpStatusCode.Conflict);
    _service.Setup(s => s.AddAsync(1, 2))
        .ThrowsAsync(conflictException);

    // Act
    var result = await _controller.Add(viewModel);

    // Assert
    var redirectResult = Assert.IsType<RedirectToActionResult>(result);
    Assert.Equal("This resource is already associated.", _controller.TempData["WarningMessage"]);
}

Examples

Real-world case: Issue #708 AddPlatform

Problem: Adding a social media platform to an engagement returns 409 if already associated. Original code showed generic error.

Solution:

  • EngagementsController.AddPlatform POST catches HttpRequestException
  • 409 → TempData["WarningMessage"] = "This platform is already associated with this engagement."
  • Other errors → TempData["ErrorMessage"] with technical details

Files:

  • src/JosephGuadagno.Broadcasting.Web/Controllers/EngagementsController.cs (lines 250-280)
  • src/JosephGuadagno.Broadcasting.Web/Views/Shared/_Layout.cshtml (lines 148-161)
  • src/JosephGuadagno.Broadcasting.Web.Tests/Controllers/EngagementsControllerTests.cs (AddPlatform tests)

Anti-Patterns

❌ Treat all HttpRequestException the same

catch (HttpRequestException ex)
{
    TempData["ErrorMessage"] = $"Failed: {ex.Message}"; // ← No differentiation
}

Problem: User can't tell if retry is safe or if something is broken.

❌ Suppress 409 entirely

if (ex.StatusCode == HttpStatusCode.Conflict)
{
    // Silent ignore ← User has no feedback
}

Problem: User doesn't know the operation was a no-op.

❌ Treat 409 as success

if (ex.StatusCode == HttpStatusCode.Conflict)
{
    TempData["SuccessMessage"] = "Resource added successfully."; // ← Misleading
}

Problem: User thinks resource was just added when it was already there.

Guidelines

  1. 409 Conflict: Use warning-level message ("This resource is already..."). Safe to retry, benign outcome.
  2. 404 Not Found (on add/update): Error-level message. Parent resource missing or ID invalid.
  3. 400 Bad Request: Error-level message with details. Validation or contract issue.
  4. 500 Server Error: Error-level message. Log details, show generic user message.

HTTP Status Code Reference for Web Controllers

Status CodeLevelUser Message ExampleRetry Safe?
200/201/204Success"Resource added successfully."N/A
400Error"Invalid request: {details}"No (fix data)
404Error"Resource not found."No
409Warning"This resource is already associated."Yes (no-op)
422Error"Validation failed: {details}"No (fix data)
500Error"An error occurred. Please try again later."Maybe

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Standard collaboration patterns for all squad agents — worktree awareness, decisions, cross-agent communication

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

Shared hard rules enforced across all squad agents

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations with extensive frameworks, testing methodologies, and educational content.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

Migrate API controller scope checks to framework-enforced authorization policies while preserving ownership checks.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

Review API DTO implementations for contract/domain separation, mapping patterns, and REST compliance

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

Register shared claims transformation and hierarchical role policies in the API without breaking existing scope enforcement.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

jguadagno/jjgnet-broadcast182026년 8월 4일 업데이트

jguadagno의 스킬 모두 보기

이 스킬의 문제 신고