skip to content

A C# quote gateway catches HttpRequestException and throws new CarrierUnavailableException(ex.Message); what do callers lose, and how should the wrap be written?

level: seniorimportance: should knowfreq 40%

answer

  1. the cause behind the message
  2. the message-plus-inner constructor
  3. the arrow line in ToString
  4. GetBaseException walks the chain
  5. wrap once, at the boundary

basics

~20 s

Passing only ex.Message throws away the original exception: its type, stack trace, properties and its own inner chain. Pass it as innerException so InnerException, GetBaseException and ToString keep the cause, and wrap only at the layer boundary.

solid answer

~40 s

Wrapping translates a low-level failure into your layer's vocabulary: callers of the quote library catch `CarrierUnavailableException` without knowing it talks HTTP. But `new CarrierUnavailableException(ex.Message)` keeps only a string, so the `HttpRequestException` itself, its `StatusCode` and `HttpRequestError`, its stack trace and anything nested inside it are gone, and the logged trace starts in the gateway. Use the `(string message, Exception innerException)` constructor instead: `InnerException` holds the original, `GetBaseException()` walks to the innermost cause, and `ToString()` prints the inner exception after ` ---> ` with its own frames, then `--- End of inner exception stack trace ---`. Wrap once, at the boundary, and only failures the caller cannot prevent; let your own `ArgumentException`s and `OperationCanceledException` through unchanged, and use `throw;` when you have nothing to add.

code

csharp · 40 lines
csharp
try
{
    new QuoteGateway().GetRate("PARCEL-EU");
}
catch (CarrierUnavailableException e)
{
    Console.WriteLine($"Caught:    {e.GetType().Name} for {e.CarrierCode}");
    Console.WriteLine($"Inner:     {e.InnerException?.GetType().Name}");
    Console.WriteLine($"Base:      {e.GetBaseException().Message}");
    Console.WriteLine($"ToString shows the cause: {e.ToString().Contains(" ---> System.Net.Http.HttpRequestException")}");
}

class QuoteGateway
{
    public decimal GetRate(string carrierCode)
    {
        try
        {
            return CallCarrierApi(carrierCode);
        }
        catch (HttpRequestException ex)
        {
            throw new CarrierUnavailableException(carrierCode, $"Carrier {carrierCode} is unavailable.", ex);
        }
    }

    private static decimal CallCarrierApi(string carrierCode) =>
        throw new HttpRequestException("Connection refused (rates.example.test:443)");
}

public sealed class CarrierUnavailableException : Exception
{
    public CarrierUnavailableException() { }
    public CarrierUnavailableException(string message) : base(message) { }
    public CarrierUnavailableException(string message, Exception innerException) : base(message, innerException) { }
    public CarrierUnavailableException(string carrierCode, string message, Exception innerException)
        : base(message, innerException) => CarrierCode = carrierCode;

    public string? CarrierCode { get; }
}

go deeper

for a junior

Recall that the message-plus-inner constructor keeps the original exception in InnerException, and that ex.Message alone loses the type and stack trace.

for a middle

Explain how InnerException, GetBaseException and ToString expose the chain, including the arrow line and the end-of-inner-trace marker.

for a senior

Decide where the boundary is, wrap only environmental failures there, pass caller bugs and cancellation through, and make sure logs record the whole chain.

for a principal

Make wrapping a library-wide rule with one boundary per external dependency, so every service sees the same domain types and incident logs always carry the original cause.

## What wrapping is for A shipping-quote library calls carrier APIs over HTTP. Its callers, three internal services, should not have to know that: they want to tell "the carrier is down, try later" from "your request is wrong" from "there is a bug". So the gateway catches the transport failure and throws an exception from the library's own vocabulary: ```csharp catch (HttpRequestException ex) { throw new CarrierUnavailableException(carrierCode, $"Carrier {carrierCode} is unavailable.", ex); } ``` The `ex` passed last becomes the new exception's **`InnerException`**. The new exception describes the failure in the caller's terms; the inner one keeps the evidence of what actually happened. ## What ex.Message keeps and what it drops | Information | `new X(ex.Message)` | `new X(message, ex)` | |---|---|---| | The original type (`HttpRequestException`) | lost | kept as `InnerException` | | The original stack trace, down to the socket call | lost | kept, printed by `ToString()` | | Properties such as `StatusCode` and `HttpRequestError` | lost | readable on `InnerException` | | The original's own inner exceptions | lost | kept, the chain continues | | The original message text | copied | kept, plus your own message | With the message-only version, an engineer reading the log sees a `CarrierUnavailableException` whose trace begins in `QuoteGateway.GetRate` and has to guess whether DNS, TLS, a refused connection or a timeout caused it. ## Reading the chain - **`InnerException`** is the exception passed to the constructor, or `null`. - **`GetBaseException()`** follows `InnerException` until it reaches the innermost exception and returns it; the BCL source is a simple loop over the chain. - **`ToString()`** prints the outer type and message, then ` ---> ` followed by the inner exception's `ToString()`, then `--- End of inner exception stack trace ---`, then the outer exception's own frames. Logging `ex.ToString()`, or passing the exception object to a logger that formats it that way, keeps the whole chain; logging only `ex.Message` throws it away a second time. - **Pattern matching** reads the cause without string parsing: `if (e.InnerException is HttpRequestException { StatusCode: HttpStatusCode.ServiceUnavailable })` lets a caller react to a 503 differently from a refused connection, which a message-only wrap makes impossible. - `AggregateException` holds several inner exceptions in `InnerExceptions`; the way tasks use it is covered with async code. ## Where and what to wrap 1. **At a boundary, once.** Wrap where your layer's vocabulary begins, typically the class that talks to the outside system. If every layer wraps again, the useful exception ends up four levels deep. 2. **Only failures the caller cannot prevent.** A refused connection or a timeout is environmental and belongs in `CarrierUnavailableException`. 3. **Not your own contract violations.** An `ArgumentNullException` from your own validation means the caller has a bug; wrapping it in a "carrier unavailable" type would send them looking at the network. 4. **Not cancellation.** `OperationCanceledException` means someone asked the operation to stop; wrapping it turns a deliberate cancel into an apparent outage. 5. **Not with a broad catch.** `catch (Exception ex) { throw new CarrierUnavailableException(..., ex); }` also wraps `NullReferenceException` and every other bug as an outage. Catch the specific transport exceptions. 6. **Not when you add nothing.** If the caller would want the original type anyway, rethrow with `throw;`, which keeps the original stack trace (the difference from `throw ex;` is covered with throwing and catching). ## Adding context without changing the type Sometimes the original type is right but a log needs more context. Exception has a `Data` dictionary for that, and the custom type can expose a read-only property such as `CarrierCode`. A property is better when callers act on the value, because it is typed and documented, while `Data` is an untyped bag that only logs read. Choose the outer message for the caller, not for the original: "Carrier PARCEL-EU is unavailable." tells a service operator what failed in their terms, while the inner exception's message keeps the transport detail. Copying `ex.Message` into the outer message as well only repeats it in every log line. ## In review Look for three patterns: `new SomethingException(ex.Message)` without the inner exception; `catch (Exception)` that wraps everything into one domain type; and log calls that write `ex.Message` where `ex` itself should be passed. Each one discards the information the next production incident needs. A correct wrap, run against a refused connection, gives a `CarrierUnavailableException` whose `InnerException` is the `HttpRequestException` and whose `GetBaseException().Message` is the original "Connection refused" text.

  • When is throw; better than wrapping the exception in your own type?
    When your layer has nothing to add and the caller is better served by the original type, for example in a catch that only rolls back state. `throw;` rethrows the same object with its original stack trace. Wrapping is for translating a low-level failure into the library's vocabulary at a boundary, keeping the original as `InnerException`.
  • Why should the gateway not wrap OperationCanceledException as CarrierUnavailableException?
    Cancellation means the caller, or a timeout it configured, asked the operation to stop; it is not a carrier failure. Wrapping it makes callers log an outage and possibly retry work they deliberately cancelled. Let `OperationCanceledException` propagate unchanged so the code that requested cancellation recognises it.

Wrapping is a cover letter stapled to the original fault report: the letter explains the problem in the reader's terms, and the report underneath still holds the evidence. Retyping one line of the report into the letter and shredding the rest leaves the reader guessing.

  • Wraps with new X(ex.Message) and drops the original exception
  • Catches Exception and wraps every failure as a carrier outage
  • Wraps again in every layer, burying the cause several levels deep
  • Logs only ex.Message, so the inner chain never reaches the log
  • Wraps OperationCanceledException as a domain failure