/

Exception Handling

ByteHide Logger captures full exception details including stack traces, inner exceptions, and custom context for comprehensive error tracking.

Basic Exception Logging

Simple Exception Logging

Java
try {
    riskyOperation();
} catch (Exception e) {
    Log.error("Operation failed", e);
}

Critical Exceptions

Java
try {
    initializeDatabase();
} catch (Exception e) {
    Log.critical("Database initialization failed", e);
    System.exit(1);
}

Fluent Exception Logging

Exception with Tags

Java
try {
    processPayment(request);
} catch (Exception e) {
    Log.withTags("payment", "error")
       .withException(e)
       .error("Payment processing failed");
}

Exception with Context

Java
try {
    processOrder(orderId);
} catch (Exception e) {
    Log.withContext("orderId", orderId)
       .withContext("customerId", customerId)
       .withException(e)
       .error("Order processing failed");
}

Exception with Correlation ID

Java
try {
    processRequest(request);
} catch (Exception e) {
    Log.withCorrelationId(correlationId)
       .withTags("api", "error")
       .withException(e)
       .error("Request processing failed");
}

Direct API Exception Logging

Java
// Exception only
Log.error("Database connection failed", exception);

// Exception with tags and context
Log.error("Payment failed",
    Arrays.asList("payment", "critical"),
    Map.of("amount", 99.99, "currency", "USD"),
    exception
);

Nested Exception Handling

Java
public void processOrder(String orderId) {
    try {
        validateOrder(orderId);
        processPayment(orderId);
        shipOrder(orderId);
    } catch (ValidationException e) {
        Log.withTags("validation")
           .withException(e)
           .warn("Order validation failed");
        throw e;
    } catch (PaymentException e) {
        Log.withTags("payment", "critical")
           .withException(e)
           .error("Payment processing failed");
        throw e;
    } catch (Exception e) {
        Log.withTags("order", "unexpected")
           .withException(e)
           .critical("Unexpected error during order processing");
        throw e;
    }
}

Best Practices

Exception Logging Best Practices

  • Always include the exception object for full stack trace capture
  • Use appropriate log levels (Warn for recoverable, Error for failures, Critical for system failures)
  • Add context to help identify the source and impact of errors
  • Use correlation IDs to track errors across distributed systems
  • Don't catch and swallow exceptions without logging

Next Steps

Previous
Tags