Skip to content

07 05 Result Integration

Cyberdyne Development edited this page Jan 19, 2026 · 3 revisions

Result Integration

MessageLogging integrates with the Result pattern. Log methods return IGenericMessage which can be passed directly to GenericResult.Failure().

Pattern

From OrderService.cs:115-126:

public IGenericResult<Order> GetOrder(string orderId)
{
    // Simulate order not found
    if (orderId.StartsWith("NOTFOUND"))
    {
        // Log AND return failure - the message is both logged and returned
        return GenericResult<Order>.Failure(
            OrderLog.OrderNotFound(_logger, orderId));
    }

    return GenericResult<Order>.Success(new Order { OrderId = orderId, Status = "Found" });
}

Benefits

  1. Single source of truth - Message defined once in attribute
  2. Always logged - Can't forget to log
  3. Consistent messages - Same text in log and result
  4. Type-safe - Parameters validated at compile time

Wrong vs Correct Patterns

Avoid string literals and separate logging:

// WRONG: String literal - no structured logging
return GenericResult.Failure("Order not found");

// WRONG: Separate logging and result - message duplication
_logger.LogWarning("Order not found: {Id}", orderId);
return GenericResult.Failure(new GenericMessage("Order not found"));

// CORRECT: MessageLogging method - logs AND returns in one call
return GenericResult<Order>.Failure(
    OrderLog.OrderNotFound(_logger, orderId));

Exception Handling

For exceptions, use methods that accept Exception. Note that the exception parameter comes after ILogger:

From OrderLog.cs:165-172:

[MessageLogging(
    EventId = 8034,
    Level = LogLevel.Error,
    Message = "Order '{orderId}': Unexpected error during processing")]
public static partial IGenericMessage ProcessingException(
    ILogger logger,
    Exception exception,
    string orderId);

From OrderService.cs:82-88:

catch (Exception ex)
{
    // CRITICAL PATTERN: Catch → Log → Return (never rethrow!)
    // The message is logged AND returned
    return GenericResult<Order>.Failure(
        OrderLog.ProcessingException(_logger, ex, orderId));
}

Next Steps

  • ResultCodes - Structured, type-safe error codes (alternative to MessageLogging for error handling)
  • Overview - Return to MessageLogging overview
  • TypeCollections - Understanding the TypeCollection pattern

Clone this wiki locally