CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-alibaba-nacos--nacos-api

Nacos API package providing interfaces and common classes for dynamic service discovery, configuration management, and service management in cloud native applications and microservices

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception hierarchy with specific error codes and handling patterns for robust error management in Nacos operations. Essential for building resilient applications with proper error handling and recovery mechanisms.

Capabilities

NacosException

Main exception class for all Nacos operations providing structured error information with specific error codes and detailed error messages.

/**
 * Main exception class for Nacos operations
 */
class NacosException extends Exception {
    /** Error code for this exception */
    private int errCode = SERVER_ERROR;
    
    /** Error message */
    private String errMsg;
    
    /** Client error codes (negative values) */
    public static final int CLIENT_INVALID_PARAM = -400;
    public static final int CLIENT_OVER_THRESHOLD = -503;
    public static final int CLIENT_DISCONNECT = -401;
    public static final int CLIENT_INVALID_SERVER_STATUS = -402;
    public static final int CLIENT_NOT_SUPPORT = -403;
    
    /** Server error codes (positive values) */
    public static final int INVALID_PARAM = 400;
    public static final int NO_RIGHT = 403;
    public static final int NOT_FOUND = 404;
    public static final int CONFLICT = 409;
    public static final int SERVER_ERROR = 500;
    public static final int BAD_GATEWAY = 502;
    public static final int OVER_THRESHOLD = 503;
    public static final int ASYNC_TIMEOUT = 504;
    
    /**
     * Default constructor with generic server error
     */
    public NacosException();
    
    /**
     * Constructor with error code and message
     * @param errCode Specific error code
     * @param errMsg Error message
     */
    public NacosException(int errCode, String errMsg);
    
    /**
     * Constructor with error code and cause
     * @param errCode Specific error code
     * @param throwable Underlying cause
     */
    public NacosException(int errCode, Throwable throwable);
    
    /**
     * Constructor with error code, message, and cause
     * @param errCode Specific error code
     * @param errMsg Error message
     * @param throwable Underlying cause
     */
    public NacosException(int errCode, String errMsg, Throwable throwable);
    
    /**
     * Get error code
     * @return Error code
     */
    public int getErrCode();
    
    /**
     * Set error code
     * @param errCode Error code
     */
    public void setErrCode(int errCode);
    
    /**
     * Get error message
     * @return Error message
     */
    public String getErrMsg();
    
    /**
     * Set error message
     * @param errMsg Error message
     */
    public void setErrMsg(String errMsg);
    
    /**
     * Check if error is client-side
     * @return true if error code is negative (client error)
     */
    public boolean isClientError();
    
    /**
     * Check if error is server-side
     * @return true if error code is positive (server error)
     */
    public boolean isServerError();
    
    /**
     * Get formatted error message including error code
     */
    @Override
    public String getMessage();
    
    /**
     * Convert to string representation
     */
    @Override
    public String toString();
}

Runtime Exceptions

Runtime exception classes for situations that don't require explicit handling but provide specific error information.

/**
 * Runtime exception for Nacos operations that don't require explicit handling
 */
class NacosRuntimeException extends RuntimeException {
    /** Error code */
    private int errorCode;
    
    /**
     * Default constructor
     */
    public NacosRuntimeException();
    
    /**
     * Constructor with message
     * @param message Error message
     */
    public NacosRuntimeException(String message);
    
    /**
     * Constructor with message and cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public NacosRuntimeException(String message, Throwable cause);
    
    /**
     * Constructor with cause
     * @param cause Underlying cause
     */
    public NacosRuntimeException(Throwable cause);
    
    /**
     * Constructor with error code and message
     * @param errorCode Specific error code
     * @param message Error message
     */
    public NacosRuntimeException(int errorCode, String message);
    
    /**
     * Constructor with error code, message, and cause
     * @param errorCode Specific error code
     * @param message Error message
     * @param cause Underlying cause
     */
    public NacosRuntimeException(int errorCode, String message, Throwable cause);
    
    /**
     * Get error code
     * @return Error code
     */
    public int getErrorCode();
    
    /**
     * Set error code
     * @param errorCode Error code
     */
    public void setErrorCode(int errorCode);
}

/**
 * API-specific exception for invalid API usage
 */
class NacosApiException extends NacosRuntimeException {
    /**
     * Constructor with message
     * @param message Error message
     */
    public NacosApiException(String message);
    
    /**
     * Constructor with message and cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public NacosApiException(String message, Throwable cause);
    
    /**
     * Constructor with error code and message
     * @param errorCode Specific error code
     * @param message Error message
     */
    public NacosApiException(int errorCode, String message);
}

Serialization Exceptions

Specialized exceptions for data serialization and deserialization operations.

/**
 * Exception for serialization errors
 */
class NacosSerializationException extends NacosRuntimeException {
    /**
     * Constructor with message
     * @param message Error message
     */
    public NacosSerializationException(String message);
    
    /**
     * Constructor with message and cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public NacosSerializationException(String message, Throwable cause);
    
    /**
     * Constructor with cause
     * @param cause Underlying cause
     */
    public NacosSerializationException(Throwable cause);
}

/**
 * Exception for deserialization errors
 */
class NacosDeserializationException extends NacosRuntimeException {
    /** Target class that failed to deserialize */
    private final Class<?> targetClass;
    
    /**
     * Constructor with message
     * @param message Error message
     */
    public NacosDeserializationException(String message);
    
    /**
     * Constructor with message and cause
     * @param message Error message
     * @param cause Underlying cause
     */
    public NacosDeserializationException(String message, Throwable cause);
    
    /**
     * Constructor with target class and cause
     * @param targetClass Class that failed to deserialize
     * @param cause Underlying cause
     */
    public NacosDeserializationException(Class<?> targetClass, Throwable cause);
    
    /**
     * Constructor with message, target class, and cause
     * @param message Error message
     * @param targetClass Class that failed to deserialize
     * @param cause Underlying cause
     */
    public NacosDeserializationException(String message, Class<?> targetClass, Throwable cause);
    
    /**
     * Get target class that failed to deserialize
     * @return Target class
     */
    public Class<?> getTargetClass();
}

Error Code Utilities

Utility classes for working with error codes and exception classification.

/**
 * Utility class for error code operations
 */
class ErrorCodeUtils {
    /**
     * Check if error code represents a client error
     * @param errorCode Error code to check
     * @return true if client error (negative)
     */
    public static boolean isClientError(int errorCode);
    
    /**
     * Check if error code represents a server error
     * @param errorCode Error code to check
     * @return true if server error (positive)
     */
    public static boolean isServerError(int errorCode);
    
    /**
     * Check if error code represents a timeout
     * @param errorCode Error code to check
     * @return true if timeout error
     */
    public static boolean isTimeoutError(int errorCode);
    
    /**
     * Check if error code represents a parameter validation error
     * @param errorCode Error code to check
     * @return true if parameter error
     */
    public static boolean isParameterError(int errorCode);
    
    /**
     * Check if error code represents an authentication/authorization error
     * @param errorCode Error code to check
     * @return true if auth error
     */
    public static boolean isAuthError(int errorCode);
    
    /**
     * Get human-readable error type description
     * @param errorCode Error code
     * @return Error type description
     */
    public static String getErrorTypeDescription(int errorCode);
    
    /**
     * Create NacosException from error code
     * @param errorCode Error code
     * @param message Error message
     * @return New NacosException instance
     */
    public static NacosException createException(int errorCode, String message);
    
    /**
     * Create NacosException from error code with cause
     * @param errorCode Error code
     * @param message Error message
     * @param cause Underlying cause
     * @return New NacosException instance
     */
    public static NacosException createException(int errorCode, String message, Throwable cause);
}

/**
 * Exception factory for creating common Nacos exceptions
 */
class NacosExceptionFactory {
    /**
     * Create invalid parameter exception
     * @param paramName Parameter name that is invalid
     * @param paramValue Parameter value that is invalid
     * @return NacosException for invalid parameter
     */
    public static NacosException invalidParameter(String paramName, Object paramValue);
    
    /**
     * Create service not found exception
     * @param serviceName Service name that was not found
     * @return NacosException for service not found
     */
    public static NacosException serviceNotFound(String serviceName);
    
    /**
     * Create configuration not found exception
     * @param dataId Configuration data ID
     * @param group Configuration group
     * @return NacosException for configuration not found
     */
    public static NacosException configNotFound(String dataId, String group);
    
    /**
     * Create connection timeout exception
     * @param timeoutMs Timeout in milliseconds
     * @return NacosException for timeout
     */
    public static NacosException connectionTimeout(long timeoutMs);
    
    /**
     * Create server unavailable exception
     * @param serverAddr Server address that is unavailable
     * @return NacosException for server unavailable
     */
    public static NacosException serverUnavailable(String serverAddr);
    
    /**
     * Create permission denied exception
     * @param resource Resource that access was denied to
     * @param operation Operation that was denied
     * @return NacosException for permission denied
     */
    public static NacosException permissionDenied(String resource, String operation);
}

Usage Examples

Basic Exception Handling

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.naming.NamingService;

public class BasicExceptionHandling {
    
    // Configuration operations with exception handling
    public String getConfigSafely(ConfigService configService, String dataId, String group) {
        try {
            return configService.getConfig(dataId, group, 5000);
            
        } catch (NacosException e) {
            System.err.printf("Failed to get config %s:%s - Error %d: %s%n", 
                group, dataId, e.getErrCode(), e.getErrMsg());
            
            // Handle specific error cases
            switch (e.getErrCode()) {
                case NacosException.NOT_FOUND:
                    System.out.println("Configuration not found, using default values");
                    return getDefaultConfig(dataId);
                    
                case NacosException.ASYNC_TIMEOUT:
                    System.out.println("Request timed out, retrying with longer timeout");
                    return retryGetConfig(configService, dataId, group);
                    
                case NacosException.NO_RIGHT:
                    System.err.println("Permission denied, check authentication");
                    throw new RuntimeException("Authentication required", e);
                    
                case NacosException.SERVER_ERROR:
                    System.err.println("Server error, will retry later");
                    return getCachedConfig(dataId, group);
                    
                default:
                    System.err.println("Unexpected error occurred");
                    throw new RuntimeException("Configuration retrieval failed", e);
            }
        }
    }
    
    // Service registration with comprehensive error handling
    public boolean registerServiceSafely(NamingService namingService, String serviceName, 
                                       String ip, int port) {
        try {
            namingService.registerInstance(serviceName, ip, port);
            System.out.printf("Successfully registered %s at %s:%d%n", serviceName, ip, port);
            return true;
            
        } catch (NacosException e) {
            System.err.printf("Failed to register service %s - Error %d: %s%n", 
                serviceName, e.getErrCode(), e.getErrMsg());
            
            if (e.isClientError()) {
                // Client-side errors (negative error codes)
                handleClientError(e, serviceName, ip, port);
            } else if (e.isServerError()) {
                // Server-side errors (positive error codes)
                handleServerError(e, serviceName, ip, port);
            }
            
            return false;
        }
    }
    
    private void handleClientError(NacosException e, String serviceName, String ip, int port) {
        switch (e.getErrCode()) {
            case NacosException.CLIENT_INVALID_PARAM:
                System.err.printf("Invalid parameters for service registration: %s at %s:%d%n", 
                    serviceName, ip, port);
                // Validate and fix parameters
                break;
                
            case NacosException.CLIENT_DISCONNECT:
                System.err.println("Client disconnected from server, attempting reconnection");
                // Trigger reconnection logic
                break;
                
            case NacosException.CLIENT_OVER_THRESHOLD:
                System.err.println("Client request rate exceeded, backing off");
                // Implement backoff strategy
                break;
                
            default:
                System.err.println("Unknown client error: " + e.getErrMsg());
                break;
        }
    }
    
    private void handleServerError(NacosException e, String serviceName, String ip, int port) {
        switch (e.getErrCode()) {
            case NacosException.SERVER_ERROR:
                System.err.println("Server internal error, will retry registration");
                // Schedule retry
                break;
                
            case NacosException.OVER_THRESHOLD:
                System.err.println("Server overloaded, backing off");
                // Implement exponential backoff
                break;
                
            case NacosException.BAD_GATEWAY:
                System.err.println("Bad gateway, checking server connectivity");
                // Check network connectivity
                break;
                
            default:
                System.err.println("Unknown server error: " + e.getErrMsg());
                break;
        }
    }
}

Exception Classification and Recovery

import com.alibaba.nacos.api.exception.ErrorCodeUtils;
import com.alibaba.nacos.api.exception.NacosExceptionFactory;

public class ExceptionClassificationExample {
    
    // Classify exceptions for different handling strategies
    public void handleExceptionWithClassification(NacosException e, String operation) {
        System.out.printf("Operation '%s' failed with error %d: %s%n", 
            operation, e.getErrCode(), e.getErrMsg());
        
        // Classify error type
        if (ErrorCodeUtils.isTimeoutError(e.getErrCode())) {
            handleTimeoutError(e, operation);
        } else if (ErrorCodeUtils.isParameterError(e.getErrCode())) {
            handleParameterError(e, operation);
        } else if (ErrorCodeUtils.isAuthError(e.getErrCode())) {
            handleAuthError(e, operation);
        } else if (ErrorCodeUtils.isClientError(e.getErrCode())) {
            handleGenericClientError(e, operation);
        } else if (ErrorCodeUtils.isServerError(e.getErrCode())) {
            handleGenericServerError(e, operation);
        } else {
            handleUnknownError(e, operation);
        }
    }
    
    private void handleTimeoutError(NacosException e, String operation) {
        System.out.println("Timeout detected, implementing retry with backoff");
        
        // Implement exponential backoff retry
        RetryPolicy.builder()
            .withMaxAttempts(3)
            .withExponentialBackoff(1000, 5000)
            .retry(() -> retryOperation(operation));
    }
    
    private void handleParameterError(NacosException e, String operation) {
        System.err.println("Parameter validation failed:");
        System.err.println("  Error: " + ErrorCodeUtils.getErrorTypeDescription(e.getErrCode()));
        System.err.println("  Suggestion: Check input parameters and API documentation");
        
        // Log parameter details for debugging
        logParameterValidationFailure(operation, e);
    }
    
    private void handleAuthError(NacosException e, String operation) {
        System.err.println("Authentication/Authorization failed:");
        System.err.println("  Check credentials and permissions");
        
        // Attempt to refresh authentication
        if (refreshAuthentication()) {
            System.out.println("Authentication refreshed, retrying operation");
            retryOperation(operation);
        } else {
            System.err.println("Authentication refresh failed, manual intervention required");
            alertAdministrator("Authentication failure for operation: " + operation);
        }
    }
    
    private void handleGenericClientError(NacosException e, String operation) {
        System.err.printf("Client error %d: %s%n", e.getErrCode(), e.getErrMsg());
        
        // Log for debugging
        logClientError(operation, e);
        
        // Most client errors are not recoverable automatically
        throw new RuntimeException("Client error in operation: " + operation, e);
    }
    
    private void handleGenericServerError(NacosException e, String operation) {
        System.err.printf("Server error %d: %s%n", e.getErrCode(), e.getErrMsg());
        
        // Server errors might be transient, implement retry
        if (isRetriableServerError(e.getErrCode())) {
            System.out.println("Retriable server error, scheduling retry");
            scheduleRetry(operation, calculateBackoffDelay(e.getErrCode()));
        } else {
            System.err.println("Non-retriable server error, alerting administrators");
            alertAdministrator("Server error in operation: " + operation + " - " + e.getErrMsg());
        }
    }
    
    private void handleUnknownError(NacosException e, String operation) {
        System.err.printf("Unknown error %d: %s%n", e.getErrCode(), e.getErrMsg());
        
        // Log for investigation
        logUnknownError(operation, e);
        
        // Conservative approach - don't retry unknown errors
        throw new RuntimeException("Unknown error in operation: " + operation, e);
    }
}

Custom Exception Handling Framework

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.function.Function;

public class NacosExceptionHandler {
    
    // Generic exception handling wrapper
    public static <T> CompletableFuture<T> handleAsync(Supplier<T> operation, String operationName) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return operation.get();
            } catch (NacosException e) {
                throw new RuntimeException(createDetailedErrorMessage(e, operationName), e);
            }
        });
    }
    
    // Exception handling with retry policy
    public static <T> T handleWithRetry(Supplier<T> operation, String operationName, 
                                       int maxRetries, long delayMs) throws NacosException {
        NacosException lastException = null;
        
        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            try {
                return operation.get();
                
            } catch (NacosException e) {
                lastException = e;
                
                // Don't retry on certain error types
                if (!isRetriableError(e)) {
                    throw e;
                }
                
                if (attempt < maxRetries) {
                    System.out.printf("Attempt %d/%d failed for %s, retrying in %dms%n", 
                        attempt + 1, maxRetries + 1, operationName, delayMs);
                    
                    try {
                        Thread.sleep(delayMs * (attempt + 1)); // Linear backoff
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new NacosException(NacosException.CLIENT_DISCONNECT, 
                            "Operation interrupted", ie);
                    }
                } else {
                    System.err.printf("All %d attempts failed for %s%n", 
                        maxRetries + 1, operationName);
                }
            }
        }
        
        throw lastException;
    }
    
    // Exception handling with circuit breaker pattern
    public static class CircuitBreakerExceptionHandler {
        private final AtomicInteger failureCount = new AtomicInteger(0);
        private volatile long lastFailureTime = 0;
        private volatile boolean circuitOpen = false;
        
        private final int failureThreshold;
        private final long circuitOpenTimeMs;
        
        public CircuitBreakerExceptionHandler(int failureThreshold, long circuitOpenTimeMs) {
            this.failureThreshold = failureThreshold;
            this.circuitOpenTimeMs = circuitOpenTimeMs;
        }
        
        public <T> T execute(Supplier<T> operation, String operationName) throws NacosException {
            // Check if circuit is open
            if (isCircuitOpen()) {
                throw NacosExceptionFactory.serverUnavailable(
                    "Circuit breaker is open for operation: " + operationName);
            }
            
            try {
                T result = operation.get();
                
                // Success - reset circuit
                resetCircuit();
                return result;
                
            } catch (NacosException e) {
                // Record failure
                recordFailure();
                
                // Check if circuit should open
                if (shouldOpenCircuit()) {
                    openCircuit();
                    System.err.printf("Circuit breaker opened for %s after %d failures%n", 
                        operationName, failureCount.get());
                }
                
                throw e;
            }
        }
        
        private boolean isCircuitOpen() {
            if (circuitOpen) {
                // Check if circuit should close (half-open state)
                if (System.currentTimeMillis() - lastFailureTime > circuitOpenTimeMs) {
                    circuitOpen = false;
                    failureCount.set(0);
                    System.out.println("Circuit breaker half-open, allowing test request");
                }
            }
            
            return circuitOpen;
        }
        
        private void recordFailure() {
            failureCount.incrementAndGet();
            lastFailureTime = System.currentTimeMillis();
        }
        
        private boolean shouldOpenCircuit() {
            return failureCount.get() >= failureThreshold;
        }
        
        private void openCircuit() {
            circuitOpen = true;
        }
        
        private void resetCircuit() {
            failureCount.set(0);
            circuitOpen = false;
            lastFailureTime = 0;
        }
    }
    
    // Utility methods
    private static String createDetailedErrorMessage(NacosException e, String operationName) {
        StringBuilder sb = new StringBuilder();
        sb.append("Operation '").append(operationName).append("' failed");
        sb.append(" [Error ").append(e.getErrCode()).append("]: ").append(e.getErrMsg());
        
        if (e.getCause() != null) {
            sb.append(" (Caused by: ").append(e.getCause().getMessage()).append(")");
        }
        
        return sb.toString();
    }
    
    private static boolean isRetriableError(NacosException e) {
        // Define which errors are retriable
        switch (e.getErrCode()) {
            case NacosException.ASYNC_TIMEOUT:
            case NacosException.SERVER_ERROR:
            case NacosException.BAD_GATEWAY:
            case NacosException.OVER_THRESHOLD:
            case NacosException.CLIENT_DISCONNECT:
                return true;
                
            case NacosException.INVALID_PARAM:
            case NacosException.NO_RIGHT:
            case NacosException.NOT_FOUND:
            case NacosException.CLIENT_INVALID_PARAM:
                return false; // Don't retry validation or auth errors
                
            default:
                return false; // Conservative approach for unknown errors
        }
    }
}

Exception Monitoring and Alerting

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ExceptionMonitor {
    
    private final Map<Integer, LongAdder> errorCounts = new ConcurrentHashMap<>();
    private final Map<String, LongAdder> operationErrorCounts = new ConcurrentHashMap<>();
    private final List<ExceptionRecord> recentExceptions = new CopyOnWriteArrayList<>();
    
    // Record exception occurrence
    public void recordException(NacosException e, String operation) {
        // Count by error code
        errorCounts.computeIfAbsent(e.getErrCode(), k -> new LongAdder()).increment();
        
        // Count by operation
        String key = operation + ":" + e.getErrCode();
        operationErrorCounts.computeIfAbsent(key, k -> new LongAdder()).increment();
        
        // Keep recent exceptions for analysis
        ExceptionRecord record = new ExceptionRecord(e, operation, LocalDateTime.now());
        recentExceptions.add(record);
        
        // Keep only last 1000 exceptions
        while (recentExceptions.size() > 1000) {
            recentExceptions.remove(0);
        }
        
        // Check for alerting conditions
        checkAlertConditions(e, operation);
    }
    
    // Generate exception statistics report
    public String generateReport() {
        StringBuilder report = new StringBuilder();
        report.append("=== Nacos Exception Statistics ===\n");
        report.append("Generated at: ").append(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)).append("\n\n");
        
        // Error code statistics
        report.append("Error Code Counts:\n");
        errorCounts.entrySet().stream()
            .sorted(Map.Entry.<Integer, LongAdder>comparingByValue((a, b) -> Long.compare(b.sum(), a.sum())))
            .forEach(entry -> {
                int errorCode = entry.getKey();
                long count = entry.getValue().sum();
                String errorType = ErrorCodeUtils.getErrorTypeDescription(errorCode);
                report.append(String.format("  %d (%s): %d occurrences%n", errorCode, errorType, count));
            });
        
        report.append("\nOperation Error Counts:\n");
        operationErrorCounts.entrySet().stream()
            .sorted(Map.Entry.<String, LongAdder>comparingByValue((a, b) -> Long.compare(b.sum(), a.sum())))
            .limit(10) // Top 10 operation errors
            .forEach(entry -> {
                String operation = entry.getKey();
                long count = entry.getValue().sum();
                report.append(String.format("  %s: %d occurrences%n", operation, count));
            });
        
        // Recent critical errors
        report.append("\nRecent Critical Errors:\n");
        recentExceptions.stream()
            .filter(record -> isCriticalError(record.exception.getErrCode()))
            .sorted((a, b) -> b.timestamp.compareTo(a.timestamp))
            .limit(5)
            .forEach(record -> {
                report.append(String.format("  [%s] %s - Error %d: %s%n",
                    record.timestamp.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss")),
                    record.operation,
                    record.exception.getErrCode(),
                    record.exception.getErrMsg()));
            });
        
        return report.toString();
    }
    
    // Check for conditions that require alerts
    private void checkAlertConditions(NacosException e, String operation) {
        // Alert on critical errors
        if (isCriticalError(e.getErrCode())) {
            sendAlert(String.format("Critical Nacos error in operation %s: [%d] %s", 
                operation, e.getErrCode(), e.getErrMsg()));
        }
        
        // Alert on high error rates
        String operationKey = operation + ":" + e.getErrCode();
        long count = operationErrorCounts.get(operationKey).sum();
        if (count > 0 && count % 10 == 0) { // Every 10th occurrence
            sendAlert(String.format("High error rate detected: %s has occurred %d times", 
                operationKey, count));
        }
        
        // Alert on authentication errors
        if (ErrorCodeUtils.isAuthError(e.getErrCode())) {
            sendAlert(String.format("Authentication error in operation %s: %s", 
                operation, e.getErrMsg()));
        }
    }
    
    private boolean isCriticalError(int errorCode) {
        return errorCode == NacosException.SERVER_ERROR ||
               errorCode == NacosException.NO_RIGHT ||
               errorCode == NacosException.CLIENT_DISCONNECT;
    }
    
    private void sendAlert(String message) {
        System.err.println("ALERT: " + message);
        // Integrate with alerting system (email, Slack, etc.)
    }
    
    // Exception record for tracking
    private static class ExceptionRecord {
        final NacosException exception;
        final String operation;
        final LocalDateTime timestamp;
        
        ExceptionRecord(NacosException exception, String operation, LocalDateTime timestamp) {
            this.exception = exception;
            this.operation = operation;
            this.timestamp = timestamp;
        }
    }
    
    // Get error rate for specific operation
    public double getErrorRate(String operation, Duration timeWindow) {
        LocalDateTime cutoff = LocalDateTime.now().minus(timeWindow);
        
        long totalOperations = recentExceptions.stream()
            .filter(record -> record.operation.equals(operation))
            .filter(record -> record.timestamp.isAfter(cutoff))
            .count();
        
        if (totalOperations == 0) {
            return 0.0;
        }
        
        long errorOperations = recentExceptions.stream()
            .filter(record -> record.operation.equals(operation))
            .filter(record -> record.timestamp.isAfter(cutoff))
            .filter(record -> record.exception != null)
            .count();
        
        return (double) errorOperations / totalOperations;
    }
    
    // Reset statistics
    public void reset() {
        errorCounts.clear();
        operationErrorCounts.clear();
        recentExceptions.clear();
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-com-alibaba-nacos--nacos-api

docs

ai-mcp.md

configuration.md

core-api.md

exceptions.md

index.md

naming.md

remote.md

tile.json