CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-azure--azure-core

Azure Core provides shared primitives, abstractions, and helpers for modern Java Azure SDK client libraries

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception hierarchy for Azure SDK operations, providing specialized exception types for different failure scenarios with detailed error information and HTTP response context.

Capabilities

Base Exception Classes

Core exception types that form the foundation of Azure SDK error handling.

/**
 * The base Azure service exception. This is the base class for all exceptions thrown by Azure SDK.
 */
class AzureException extends RuntimeException {
    /**
     * Constructs a new AzureException instance.
     */
    public AzureException();
    
    /**
     * Constructs a new AzureException instance with the specified detail message.
     * @param message The detail message (which is saved for later retrieval by the getMessage() method)
     */
    public AzureException(String message);
    
    /**
     * Constructs a new AzureException instance with the specified detail message and cause.
     * @param message The detail message (which is saved for later retrieval by the getMessage() method)
     * @param cause The cause (which is saved for later retrieval by the getCause() method)
     */
    public AzureException(String message, Throwable cause);
    
    /**
     * Constructs a new AzureException instance with the specified cause.
     * @param cause The cause (which is saved for later retrieval by the getCause() method)
     */
    public AzureException(Throwable cause);
    
    /**
     * Constructs a new AzureException instance.
     * @param message The detail message
     * @param cause The cause
     * @param enableSuppression Whether or not suppression is enabled or disabled
     * @param writableStackTrace Whether or not the stack trace should be writable
     */
    public AzureException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace);
}

HTTP Response Exception

Exception type that includes HTTP response information for service failures.

/**
 * Exception thrown for an invalid response with custom error information.
 */
class HttpResponseException extends AzureException {
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param response The HTTP response associated with this exception
     */
    public HttpResponseException(HttpResponse response);
    
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public HttpResponseException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public HttpResponseException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public HttpResponseException(HttpResponse response, Throwable cause);
    
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception  
     * @param cause The Throwable which caused the creation of this exception
     */
    public HttpResponseException(String message, HttpResponse response, Throwable cause);
    
    /**
     * Initializes a new instance of the HttpResponseException class.
     * @param message The exception message
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     * @param enableSuppression Whether suppression is enabled or disabled
     * @param writableStackTrace Whether the stack trace should be writable
     */
    public HttpResponseException(String message, HttpResponse response, Throwable cause, boolean enableSuppression, boolean writableStackTrace);
    
    /**
     * Gets the HTTP response that caused the exception.
     * @return The HTTP response that caused the exception
     */
    public HttpResponse getResponse();
    
    /**
     * Gets the deserialized HTTP response value.
     * @return The deserialized HTTP response value
     */
    public Object getValue();
}

Authentication Exceptions

Exceptions for authentication and authorization failures.

/**
 * Exception thrown when authentication fails.
 */
class ClientAuthenticationException extends HttpResponseException {
    /**
     * Initializes a new instance of the ClientAuthenticationException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public ClientAuthenticationException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the ClientAuthenticationException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public ClientAuthenticationException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the ClientAuthenticationException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public ClientAuthenticationException(String message, HttpResponse response, Throwable cause);
}

Resource State Exceptions

Exceptions for resource existence and modification state issues.

/**
 * Exception thrown when a resource already exists.
 */
class ResourceExistsException extends HttpResponseException {
    /**
     * Initializes a new instance of the ResourceExistsException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public ResourceExistsException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the ResourceExistsException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public ResourceExistsException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the ResourceExistsException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public ResourceExistsException(String message, HttpResponse response, Throwable cause);
}

/**
 * Exception thrown when a resource is not found.
 */
class ResourceNotFoundException extends HttpResponseException {
    /**
     * Initializes a new instance of the ResourceNotFoundException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public ResourceNotFoundException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the ResourceNotFoundException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public ResourceNotFoundException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the ResourceNotFoundException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public ResourceNotFoundException(String message, HttpResponse response, Throwable cause);
}

/**
 * Exception thrown when a resource has been modified.
 */
class ResourceModifiedException extends HttpResponseException {
    /**
     * Initializes a new instance of the ResourceModifiedException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public ResourceModifiedException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the ResourceModifiedException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public ResourceModifiedException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the ResourceModifiedException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public ResourceModifiedException(String message, HttpResponse response, Throwable cause);
}

HTTP and Data Exceptions

Exceptions for HTTP protocol and data processing issues.

/**
 * Exception thrown when an HTTP request fails.
 */
class HttpRequestException extends AzureException {
    /**
     * Initializes a new instance of the HttpRequestException class.
     * @param message The exception message
     */
    public HttpRequestException(String message);
    
    /**
     * Initializes a new instance of the HttpRequestException class.
     * @param message The exception message
     * @param cause The Throwable which caused the creation of this exception
     */
    public HttpRequestException(String message, Throwable cause);
    
    /**
     * Initializes a new instance of the HttpRequestException class.
     * @param cause The Throwable which caused the creation of this exception
     */
    public HttpRequestException(Throwable cause);
}

/**
 * Exception thrown when decoding/deserializing fails.
 */
class DecodeException extends AzureException {
    /**
     * Initializes a new instance of the DecodeException class.
     * @param message The exception message
     */
    public DecodeException(String message);
    
    /**
     * Initializes a new instance of the DecodeException class.
     * @param message The exception message
     * @param cause The Throwable which caused the creation of this exception
     */
    public DecodeException(String message, Throwable cause);
    
    /**
     * Initializes a new instance of the DecodeException class.
     * @param cause The Throwable which caused the creation of this exception
     */
    public DecodeException(Throwable cause);
}

/**
 * Exception thrown when the response body length doesn't match the expected length.
 */
class UnexpectedLengthException extends HttpResponseException {
    /**
     * Initializes a new instance of the UnexpectedLengthException class.
     * @param message The exception message
     * @param response The HTTP response associated with this exception
     */
    public UnexpectedLengthException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the UnexpectedLengthException class.
     * @param message The exception message
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public UnexpectedLengthException(String message, HttpResponse response, Throwable cause);
}

/**
 * Exception thrown when too many redirects occur.
 */
class TooManyRedirectsException extends HttpResponseException {
    /**
     * Initializes a new instance of the TooManyRedirectsException class.
     * @param message The exception message
     * @param response The HTTP response associated with this exception
     */
    public TooManyRedirectsException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the TooManyRedirectsException class.
     * @param message The exception message
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public TooManyRedirectsException(String message, HttpResponse response, Throwable cause);
}

Service Response Exception

Generic exception for service-specific response errors.

/**
 * Exception thrown for service response errors.
 */
class ServiceResponseException extends HttpResponseException {
    /**
     * Initializes a new instance of the ServiceResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     */
    public ServiceResponseException(String message, HttpResponse response);
    
    /**
     * Initializes a new instance of the ServiceResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param value The deserialized response value
     */
    public ServiceResponseException(String message, HttpResponse response, Object value);
    
    /**
     * Initializes a new instance of the ServiceResponseException class.
     * @param message The exception message or the response content if a message is not available
     * @param response The HTTP response associated with this exception
     * @param cause The Throwable which caused the creation of this exception
     */
    public ServiceResponseException(String message, HttpResponse response, Throwable cause);
}

Usage Examples

Basic Exception Handling

import com.azure.core.exception.*;
import com.azure.core.http.HttpResponse;

public class ServiceClient {
    
    public void handleBasicExceptions() {
        try {
            // Service operation that may fail
            performServiceOperation();
        } catch (ClientAuthenticationException e) {
            // Handle authentication failures
            System.err.println("Authentication failed: " + e.getMessage());
            System.err.println("Status code: " + e.getResponse().getStatusCode());
            
            // Re-authenticate or prompt for new credentials
            handleAuthenticationFailure(e);
            
        } catch (ResourceNotFoundException e) {
            // Handle missing resources
            System.err.println("Resource not found: " + e.getMessage());
            
            // Create the resource or handle gracefully
            handleMissingResource(e);
            
        } catch (ResourceExistsException e) {
            // Handle resource conflicts
            System.err.println("Resource already exists: " + e.getMessage());
            
            // Use existing resource or update it
            handleResourceConflict(e);
            
        } catch (HttpResponseException e) {
            // Handle other HTTP errors
            System.err.println("HTTP error: " + e.getMessage());
            System.err.println("Status code: " + e.getResponse().getStatusCode());
            
            // Log response details and handle appropriately
            handleGeneralHttpError(e);
            
        } catch (AzureException e) {
            // Handle all other Azure SDK exceptions
            System.err.println("Azure SDK error: " + e.getMessage());
            handleGeneralAzureError(e);
        }
    }
    
    private void performServiceOperation() {
        // Implementation
    }
    
    private void handleAuthenticationFailure(ClientAuthenticationException e) {
        // Implementation
    }
    
    private void handleMissingResource(ResourceNotFoundException e) {
        // Implementation
    }
    
    private void handleResourceConflict(ResourceExistsException e) {
        // Implementation
    }
    
    private void handleGeneralHttpError(HttpResponseException e) {
        // Implementation
    }
    
    private void handleGeneralAzureError(AzureException e) {
        // Implementation
    }
}

Reactive Exception Handling

import com.azure.core.exception.*;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import java.time.Duration;

public class ReactiveServiceClient {
    
    public Mono<String> getResourceWithRetry(String resourceId) {
        return performAsyncOperation(resourceId)
            .onErrorResume(ClientAuthenticationException.class, this::handleAuthError)
            .onErrorResume(ResourceNotFoundException.class, this::handleNotFound)
            .onErrorResume(TooManyRedirectsException.class, this::handleRedirectError)
            .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))
                .filter(this::isRetryableException)
                .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
                    return new RuntimeException("Retry exhausted after " + retrySignal.totalRetries() + " attempts");
                }));
    }
    
    private Mono<String> performAsyncOperation(String resourceId) {
        // Implementation
        return Mono.just("result");
    }
    
    private Mono<String> handleAuthError(ClientAuthenticationException e) {
        System.err.println("Authentication failed, attempting to refresh token");
        return refreshTokenAndRetry(e);
    }
    
    private Mono<String> handleNotFound(ResourceNotFoundException e) {
        System.err.println("Resource not found, creating default resource");
        return createDefaultResource();
    }
    
    private Mono<String> handleRedirectError(TooManyRedirectsException e) {
        System.err.println("Too many redirects, aborting operation");
        return Mono.error(new RuntimeException("Operation failed due to excessive redirects", e));
    }
    
    private boolean isRetryableException(Throwable e) {
        if (e instanceof HttpResponseException) {
            int statusCode = ((HttpResponseException) e).getResponse().getStatusCode();
            // Retry on server errors (5xx) and rate limiting (429)
            return statusCode >= 500 || statusCode == 429;
        }
        return e instanceof HttpRequestException || e instanceof DecodeException;
    }
    
    private Mono<String> refreshTokenAndRetry(ClientAuthenticationException e) {
        // Implementation to refresh authentication and retry
        return Mono.just("refreshed-result");
    }
    
    private Mono<String> createDefaultResource() {
        // Implementation to create a default resource
        return Mono.just("default-resource");
    }
}

Exception Information Extraction

import com.azure.core.exception.*;
import com.azure.core.http.HttpHeaders;

public class ExceptionAnalyzer {
    
    public void analyzeException(Exception e) {
        if (e instanceof HttpResponseException) {
            analyzeHttpResponseException((HttpResponseException) e);
        } else if (e instanceof AzureException) {
            analyzeAzureException((AzureException) e);
        } else {
            analyzeGeneralException(e);
        }
    }
    
    private void analyzeHttpResponseException(HttpResponseException e) {
        System.out.println("HTTP Response Exception Analysis:");
        System.out.println("Message: " + e.getMessage());
        
        HttpResponse response = e.getResponse();
        if (response != null) {
            System.out.println("Status Code: " + response.getStatusCode());
            System.out.println("Reason Phrase: " + response.getReasonPhrase());
            
            // Analyze headers
            HttpHeaders headers = response.getHeaders();
            System.out.println("Headers:");
            headers.forEach((name, value) -> 
                System.out.println("  " + name + ": " + value));
            
            // Get response body if available
            try {
                String body = response.getBodyAsString().block();
                System.out.println("Response Body: " + body);
            } catch (Exception bodyException) {
                System.out.println("Could not read response body: " + bodyException.getMessage());
            }
        }
        
        // Check for deserialized response value
        Object value = e.getValue();
        if (value != null) {
            System.out.println("Deserialized Value Type: " + value.getClass().getSimpleName());
            System.out.println("Deserialized Value: " + value.toString());
        }
        
        // Determine exception type and provide specific guidance
        if (e instanceof ClientAuthenticationException) {
            System.out.println("Recommendation: Check credentials and token expiration");
        } else if (e instanceof ResourceNotFoundException) {
            System.out.println("Recommendation: Verify resource exists and path is correct");
        } else if (e instanceof ResourceExistsException) {
            System.out.println("Recommendation: Use PUT for updates or check if resource should be replaced");
        } else if (e instanceof TooManyRedirectsException) {
            System.out.println("Recommendation: Check for redirect loops or increase redirect limit");
        }
    }
    
    private void analyzeAzureException(AzureException e) {
        System.out.println("Azure Exception Analysis:");
        System.out.println("Message: " + e.getMessage());
        System.out.println("Type: " + e.getClass().getSimpleName());
        
        if (e.getCause() != null) {
            System.out.println("Root Cause: " + e.getCause().getMessage());
            System.out.println("Root Cause Type: " + e.getCause().getClass().getSimpleName());
        }
        
        // Print stack trace for debugging
        e.printStackTrace();
    }
    
    private void analyzeGeneralException(Exception e) {
        System.out.println("General Exception Analysis:");
        System.out.println("Message: " + e.getMessage());
        System.out.println("Type: " + e.getClass().getSimpleName());
        e.printStackTrace();
    }
}

Custom Exception Handler

import com.azure.core.exception.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class CustomExceptionHandler {
    private final Map<Class<? extends Exception>, Function<Exception, String>> handlers = new ConcurrentHashMap<>();
    
    public CustomExceptionHandler() {
        setupDefaultHandlers();
    }
    
    private void setupDefaultHandlers() {
        // Register specific handlers for different exception types
        handlers.put(ClientAuthenticationException.class, this::handleAuthenticationException);
        handlers.put(ResourceNotFoundException.class, this::handleResourceNotFoundException);
        handlers.put(ResourceExistsException.class, this::handleResourceExistsException);
        handlers.put(ResourceModifiedException.class, this::handleResourceModifiedException);
        handlers.put(TooManyRedirectsException.class, this::handleTooManyRedirectsException);
        handlers.put(UnexpectedLengthException.class, this::handleUnexpectedLengthException);
        handlers.put(DecodeException.class, this::handleDecodeException);
        handlers.put(HttpRequestException.class, this::handleHttpRequestException);
        handlers.put(HttpResponseException.class, this::handleHttpResponseException);
        handlers.put(AzureException.class, this::handleAzureException);
    }
    
    public String handleException(Exception e) {
        Function<Exception, String> handler = findHandler(e.getClass());
        return handler != null ? handler.apply(e) : handleUnknownException(e);
    }
    
    private Function<Exception, String> findHandler(Class<? extends Exception> exceptionClass) {
        // Try exact match first
        Function<Exception, String> handler = handlers.get(exceptionClass);
        if (handler != null) {
            return handler;
        }
        
        // Try to find handler for parent classes
        for (Map.Entry<Class<? extends Exception>, Function<Exception, String>> entry : handlers.entrySet()) {
            if (entry.getKey().isAssignableFrom(exceptionClass)) {
                return entry.getValue();
            }
        }
        
        return null;
    }
    
    private String handleAuthenticationException(Exception e) {
        ClientAuthenticationException authEx = (ClientAuthenticationException) e;
        return String.format("Authentication failed (Status: %d). Please check your credentials and ensure they have not expired.",
            authEx.getResponse().getStatusCode());
    }
    
    private String handleResourceNotFoundException(Exception e) {
        ResourceNotFoundException notFoundEx = (ResourceNotFoundException) e;
        return String.format("The requested resource was not found (Status: %d). Please verify the resource identifier and try again.",
            notFoundEx.getResponse().getStatusCode());
    }
    
    private String handleResourceExistsException(Exception e) {
        ResourceExistsException existsEx = (ResourceExistsException) e;
        return String.format("The resource already exists (Status: %d). Use PUT to update or check if the operation is idempotent.",
            existsEx.getResponse().getStatusCode());
    }
    
    private String handleResourceModifiedException(Exception e) {
        ResourceModifiedException modifiedEx = (ResourceModifiedException) e;
        return String.format("The resource has been modified (Status: %d). Please refresh and retry with updated information.",
            modifiedEx.getResponse().getStatusCode());
    }
    
    private String handleTooManyRedirectsException(Exception e) {
        return "Too many redirects encountered. This may indicate a redirect loop or misconfigured service endpoint.";
    }
    
    private String handleUnexpectedLengthException(Exception e) {
        return "Response body length did not match expected length. The data may be corrupted or truncated.";
    }
    
    private String handleDecodeException(Exception e) {
        return "Failed to decode response data. The response format may be invalid or unsupported.";
    }
    
    private String handleHttpRequestException(Exception e) {
        return "HTTP request failed. Please check network connectivity and service availability.";
    }
    
    private String handleHttpResponseException(Exception e) {
        HttpResponseException httpEx = (HttpResponseException) e;
        int statusCode = httpEx.getResponse().getStatusCode();
        
        if (statusCode >= 400 && statusCode < 500) {
            return String.format("Client error (Status: %d). Please check the request parameters and authentication.", statusCode);
        } else if (statusCode >= 500) {
            return String.format("Server error (Status: %d). The service may be temporarily unavailable.", statusCode);
        } else {
            return String.format("Unexpected HTTP response (Status: %d).", statusCode);
        }
    }
    
    private String handleAzureException(Exception e) {
        return String.format("Azure SDK error: %s. Please check the operation parameters and try again.", e.getMessage());
    }
    
    private String handleUnknownException(Exception e) {
        return String.format("An unexpected error occurred: %s. Please contact support if the issue persists.", e.getMessage());
    }
    
    // Allow users to register custom handlers
    public <T extends Exception> void registerHandler(Class<T> exceptionClass, Function<Exception, String> handler) {
        handlers.put(exceptionClass, handler);
    }
}

Exception Reporting and Telemetry

import com.azure.core.exception.*;
import com.azure.core.util.logging.ClientLogger;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class ExceptionReporter {
    private static final ClientLogger LOGGER = new ClientLogger(ExceptionReporter.class);
    
    public void reportException(Exception e, String operationName, String clientName) {
        Map<String, Object> telemetryData = new HashMap<>();
        telemetryData.put("timestamp", Instant.now().toString());
        telemetryData.put("operation", operationName);
        telemetryData.put("client", clientName);
        telemetryData.put("exceptionType", e.getClass().getSimpleName());
        telemetryData.put("message", e.getMessage());
        
        if (e instanceof HttpResponseException) {
            HttpResponseException httpEx = (HttpResponseException) e;
            HttpResponse response = httpEx.getResponse();
            
            telemetryData.put("statusCode", response.getStatusCode());
            telemetryData.put("reasonPhrase", response.getReasonPhrase());
            
            // Add request ID if available
            String requestId = response.getHeaderValue("x-ms-request-id");
            if (requestId != null) {
                telemetryData.put("requestId", requestId);
            }
            
            // Add correlation ID if available
            String correlationId = response.getHeaderValue("x-ms-correlation-request-id");
            if (correlationId != null) {
                telemetryData.put("correlationId", correlationId);
            }
        }
        
        // Log the exception with telemetry data
        LOGGER.error("Operation failed: {}", telemetryData, e);
        
        // Send to telemetry system (implementation-specific)
        sendToTelemetrySystem(telemetryData);
    }
    
    private void sendToTelemetrySystem(Map<String, Object> telemetryData) {
        // Implementation would send data to Application Insights, custom telemetry system, etc.
        System.out.println("Telemetry: " + telemetryData);
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-com-azure--azure-core

docs

annotations.md

authentication.md

client-traits.md

cryptography.md

exceptions.md

http-client.md

http-policies.md

index.md

models.md

serialization.md

utilities.md

tile.json