Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514-thinking-32k· AnthropicHugging Face LMArena Human Preference 140K

What to do if a don't want to throw domain exception?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. User

    What to do if a don't want to throw domain exception?

  2. Claude Assistant

    Great question! There are several elegant alternatives to throwing domain exceptions. Here are the most practical approaches:

    1. Result/Either Pattern

    // Result wrapper
    public class Result<T> {
        private final T value;
        private final String error;
        private final boolean success;
        
        private Result(T value, String error, boolean success) {
            this.value = value;
            this.error = error;
            this.success = success;
        }
        
        public static <T> Result<T> success(T value) {
            return new Result<>(value, null, true);
        }
        
        public static <T> Result<T> failure(String error) {
            return new Result<>(null, error, false);
        }
        
        public boolean isSuccess() { return success; }
        public T getValue() { return value; }
        public String getError() { return error; }
    }
    
    // Domain service using Result
    @Service
    public class UserService {
        private final UserRepository userRepository;
        
        public Result<User> createUser(String name, String email) {
            if (userRepository.existsByEmail(email)) {
                return Result.failure("Email already exists");
            }
            
            if (name == null || name.trim().isEmpty()) {
                return Result.failure("Name cannot be empty");
            }
            
            User user = new User(name, email);
            User savedUser = userRepository.save(user);
            return Result.success(savedUser);
        }
    }
    
    // Controller handling Result
    @RestController
    public class UserController {
        private final UserService userService;
        
        @PostMapping("/users")
        public ResponseEntity<UserDto> createUser(@RequestBody CreateUserRequest request) {
            Result<User> result = userService.createUser(request.getName(), request.getEmail());
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(UserDto.from(result.getValue()));
            } else {
                return ResponseEntity.badRequest()
                    .body(new ErrorDto(result.getError()));
            }
        }
    }
    

    2. Validation Object Pattern

    // Validation result collector
    public class ValidationResult {
        private final List<String> errors = new ArrayList<>();
        
        public ValidationResult addError(String error) {
            errors.add(error);
            return this;
        }
        
        public ValidationResult addErrorIf(boolean condition, String error) {
            if (condition) {
                errors.add(error);
            }
            return this;
        }
        
        public boolean isValid() {
            return errors.isEmpty();
        }
        
        public List<String> getErrors() {
            return Collections.unmodifiableList(errors);
        }
    }
    
    // Domain service with validation
    @Service
    public class UserService {
        
        public ValidationResult validateUser(String name, String email) {
            ValidationResult validation = new ValidationResult();
            
            validation
                .addErrorIf(name == null || name.trim().isEmpty(), "Name is required")
                .addErrorIf(email == null || !isValidEmail(email), "Valid email is required")
                .addErrorIf(userRepository.existsByEmail(email), "Email already exists");
                
            return validation;
        }
        
        public User createUser(String name, String email) {
            ValidationResult validation = validateUser(name, email);
            
            if (!validation.isValid()) {
                // Handle validation errors without throwing
                return null; // Or return Optional.empty()
            }
            
            return userRepository.save(new User(name, email));
        }
    }
    
    // Controller
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody CreateUserRequest request) {
        ValidationResult validation = userService.validateUser(request.getName(), request.getEmail());
        
        if (!validation.isValid()) {
            return ResponseEntity.badRequest()
                .body(new ValidationErrorDto(validation.getErrors()));
        }
        
        User user = userService.createUser(request.getName(), request.getEmail());
        return ResponseEntity.ok(UserDto.from(user));
    }
    

    3. Optional-Based Approach

    // Domain service returning Optional
    @Service
    public class UserService {
        
        public Optional<User> createUser(String name, String email) {
            if (name == null || name.trim().isEmpty()) {
                return Optional.empty();
            }
            
            if (userRepository.existsByEmail(email)) {
                return Optional.empty();
            }
            
            User user = new User(name, email);
            return Optional.of(userRepository.save(user));
        }
        
        // If you need to know WHY it failed, use a separate method
        public List<String> validateUserCreation(String name, String email) {
            List<String> errors = new ArrayList<>();
            
            if (name == null || name.trim().isEmpty()) {
                errors.add("Name is required");
            }
            
            if (userRepository.existsByEmail(email)) {
                errors.add("Email already exists");
            }
            
            return errors;
        }
    }
    
    // Controller
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody CreateUserRequest request) {
        List<String> validationErrors = userService.validateUserCreation(
            request.getName(), request.getEmail());
        
        if (!validationErrors.isEmpty()) {
            return ResponseEntity.badRequest()
                .body(new ValidationErrorDto(validationErrors));
        }
        
        Optional<User> userOpt = userService.createUser(request.getName(), request.getEmail());
        
        return userOpt
            .map(user -> ResponseEntity.ok(UserDto.from(user)))
            .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
    }
    

    4. Command Pattern with Status

    // Command result
    public class CreateUserCommand {
        private final String name;
        private final String email;
        private User createdUser;
        private CommandStatus status = CommandStatus.PENDING;
        private List<String> errors = new ArrayList<>();
        
        public CreateUserCommand(String name, String email) {
            this.name = name;
            this.email = email;
        }
        
        public void markAsSuccessful(User user) {
            this.createdUser = user;
            this.status = CommandStatus.SUCCESS;
        }
        
        public void markAsFailed(String error) {
            this.errors.add(error);
            this.status = CommandStatus.FAILED;
        }
        
        // getters...
    }
    
    enum CommandStatus {
        PENDING, SUCCESS, FAILED
    }
    
    // Command handler
    @Service
    public class CreateUserCommandHandler {
        
        public CreateUserCommand handle(CreateUserCommand command) {
            if (command.getName() == null || command.getName().trim().isEmpty()) {
                command.markAsFailed("Name is required");
                return command;
            }
            
            if (userRepository.existsByEmail(command.getEmail())) {
                command.markAsFailed("Email already exists");
                return command;
            }
            
            User user = new User(command.getName(), command.getEmail());
            User savedUser = userRepository.save(user);
            command.markAsSuccessful(savedUser);
            
            return command;
        }
    }
    

    5. Functional Approach with Vavr (Third-party library)

    // Using Vavr's Either type
    import io.vavr.control.Either;
    
    @Service
    public class UserService {
        
        public Either<String, User> createUser(String name, String email) {
            if (name == null || name.trim().isEmpty()) {
                return Either.left("Name is required");
            }
            
            if (userRepository.existsByEmail(email)) {
                return Either.left("Email already exists");
            }
            
            User user = new User(name, email);
            return Either.right(userRepository.save(user));
        }
    }
    
    // Controller
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody CreateUserRequest request) {
        Either<String, User> result = userService.createUser(request.getName(), request.getEmail());
        
        return result
            .map(user -> ResponseEntity.ok(UserDto.from(user)))
            .getOrElseGet(error -> ResponseEntity.badRequest().body(new ErrorDto(error)));
    }
    

    When to use each approach:

    • Result/Either: When you want explicit success/failure handling and clear error messages
    • Validation Object: When you have multiple potential validation errors to collect
    • Optional: When failure is rare and you don't need detailed error information
    • Command Pattern: When you're using CQRS or want to track command execution state
    • Functional (Either): When you want to chain operations and handle errors functionally

    The Result pattern is often the most practical choice as it's explicit, doesn't require external libraries, and provides clear error information.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.