Dotnet exception handling

From rysweet/amplihack · View interactive version

Dotnet exception handling is an AI agent skill from the GitHub repository rysweet/amplihack. Comprehensive .NET exception handling quality improvement workflow. Auto-detects .NET projects, investigates 10 common exception handling mistakes, generates prioritized findings, and orchestrates fixes following best practices.

How to use this skill

Skill file

.NET Exception Handling Quality Improvement

Purpose

Systematic investigation and remediation of .NET exception handling anti-patterns. Detects, documents, and fixes the 10 most common exception handling mistakes in .NET applications.

Use when: Preparing for production, code quality audits, security reviews, or onboarding to a .NET codebase.

Usage

# Investigation only (default)
/dotnet-exception-handling <path-to-dotnet-project>

# Filter by severity
/dotnet-exception-handling <project-path> --priority critical

# Auto-implement all fixes
/dotnet-exception-handling <project-path> --fix-all

Arguments:

The 10 Common Mistakes

  1. Catching Exception Too Broadly - Base Exception instead of specific types
  2. Swallowing Exceptions Silently - Empty catch blocks hiding errors
  3. Using throw ex; - Resets stack traces (use throw;)
  4. Wrapping Everything in Try/Catch - Defensive coding clutter
  5. Exceptions for Control Flow - Performance overhead for expected conditions
  6. Forgetting to Await Async - Unhandled exceptions on background threads
  7. Ignoring Background Task Exceptions - Fire-and-forget losing errors
  8. Generic Exception Types - Vague new Exception() instead of specific types
  9. Losing Inner Exceptions - Breaking exception chains
  10. Missing Global Handler - No centralized error handling (stack traces exposed)

Detailed descriptions, detection patterns, and fix templates → see reference.md

Execution Workflow

Phase 1: Investigation (6 Steps)

Step 1: Project Detection

Step 2: Parallel Analysis

Step 3: Violation Detection

```bash

# Mistake #1: Broad catches

rg -P 'catch\s\(Exception\b' --glob '.cs'

# Mistake #2: Empty catches

rg -P 'catch[^{]\{\s(//[^\n])?\s\}' --glob '*.cs'

# Mistake #3: throw ex

rg 'throw\s+ex;' --glob '*.cs'

```

Step 4: Severity Classification

Step 5: Findings Report

Step 6: Knowledge Capture

Phase 2: Development (If --fix-all)

Step 7: Orchestrate Default Workflow

Step 8: Validation

Quick Start Examples

Example 1: Investigation Only

/dotnet-exception-handling ./src/MyApi

Output: Investigation report with 23 violations (1 CRITICAL, 8 HIGH, 12 MEDIUM, 2 LOW)

Example 2: Fix Critical Only

/dotnet-exception-handling ./src/MyApi --priority critical --fix-all

Output: GitHub issue + PR implementing GlobalExceptionHandler + 15 tests

Example 3: Complete Fix

/dotnet-exception-handling ./src/MyApi --fix-all

Output: 23 violations fixed, 67 tests, PR ready (CI passing)

Core Architecture Patterns

GlobalExceptionHandler (IExceptionHandler)

Centralized exception-to-HTTP mapping for ASP.NET Core:

public class GlobalExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        var (statusCode, title) = exception switch
        {
            ArgumentException => (400, "Invalid request"),
            NotFoundException => (404, "Not found"),
            ConflictException => (409, "Conflict"),
            _ => (500, "Internal server error")
        };

        httpContext.Response.StatusCode = statusCode;
        await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
        {
            Status = statusCode,
            Title = title,
            Detail = statusCode >= 500
                ? "An error occurred"
                : exception.Message
        }, cancellationToken);

        return true;
    }
}

// Registration in Program.cs
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
app.UseExceptionHandler();

Benefits: Zero stack traces, consistent responses, no try/catch in controllers

Result<T> Pattern

Railway-oriented programming for validation (no exceptions for expected conditions):

public Result<Order> ValidateOrder(CreateOrderDto dto)
{
    if (dto.Items.Count == 0)
        return Result<Order>.Failure("Order must have items");

    return Result<Order>.Success(new Order(dto));
}

// Controller usage
var result = await _service.ValidateOrder(dto);
return result.Match(
    onSuccess: order => Ok(order),
    onFailure: error => BadRequest(error)
);

Benefits: 100x faster than exceptions, explicit error handling, better composition

Complete implementations → see examples.md

Navigation Guide

When to Read Supporting Files

reference.md - Read when you need:

examples.md - Read when you need:

patterns.md - Read when you need:

Workflow Integration

This skill orchestrates two canonical workflows:

  1. Investigation Workflow (Phase 1): Scope → Explore → Analyze → Classify → Report → Capture
  2. Default Workflow (Phase 2, if --fix-all): Requirements → Architecture → TDD → Implementation → Review → CI/CD

References

Version History

Known Limitations

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.