Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-03-26-experimental· MetaHugging 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 Claudeclaude-sonnet-4-20250514-thinking-32k’s answer.
  1. User

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

  2. Meta Assistant

    If you don't want to throw domain exceptions directly (e.g., UserNotFoundException), you have several alternatives that still maintain clean architecture principles. Here are 5 approaches to handle errors without polluting your domain with exceptions:

    1. Result Pattern (Recommended)

    Return a Result object wrapping either the success value or an error state.

    // Result.java (generic class)
    public class Result<T> {
        private final T value;
        private final Error error;
        
        private Result(T value, Error error) {
            this.value = value;
            this.error = error;
        }
        
        public static <T> Result<T> success(T value) {
            return new Result<>(value, null);
        }
        
        public static <T> Result<T> failure(Error error) {
            return new Result<>(null, error);
        }
        
        public boolean isSuccess() {
            return error == null;
        }
        
        public T getValue() {
            if (error != null) throw new IllegalStateException("Result is failure");
            return value;
        }
        
        public Error getError() {
            return error;
        }
    }
    
    // Error.java (enum or class)
    public enum Error {
        USER_NOT_FOUND("User not found"),
        INVALID_CREDENTIALS("Invalid credentials");
        
        private final String message;
        Error(String message) {
            this.message = message;
        }
        public String getMessage() {
            return message;
        }
    }
    

    Usage in Service

    @Service
    public class UserService {
        public Result<User> findById(Long id) {
            return userRepository.findById(id)
                .map(Result::success)
                .orElseGet(() -> Result.failure(Error.USER_NOT_FOUND));
        }
    }
    

    Controller Handling

    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        Result<User> result = userService.findById(id);
        return result.isSuccess()
            ? ResponseEntity.ok(result.getValue())
            : ResponseEntity.status(HttpStatus.NOT_FOUND)
                             .body(result.getError().getMessage());
    }
    

    2. Optional Return Type

    Java's Optional can indicate absence of value without exceptions.

    @Service
    public class UserService {
        public Optional<User> findById(Long id) {
            return userRepository.findById(id);
        }
    }
    

    Controller

    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElseGet(() -> ResponseEntity.notFound().build());
    }
    

    Downside: Doesn't convey why the value is absent (e.g., not found vs. permission denied).

    3. Functional Error Handling with Either

    Inspired by functional programming (e.g., Vavr library).

    import io.vavr.control.Either;
    
    @Service
    public class UserService {
        public Either<Error, User> findById(Long id) {
            return userRepository.findById(id)
                .map(Either::right) // Success path
                .orElse(Either.left(Error.USER_NOT_FOUND)); // Failure path
        }
    }
    

    Controller

    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .fold(
                error -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(error.getMessage()),
                user -> ResponseEntity.ok(user)
            );
    }
    

    4. Custom Response DTO

    Always return a standardized response object.

    public class ApiResponse<T> {
        private final T data;
        private final String error;
        
        // Constructors, getters
    }
    

    Service

    @Service
    public class UserService {
        public ApiResponse<User> findById(Long id) {
            return userRepository.findById(id)
                .map(user -> new ApiResponse<>(user, null))
                .orElse(new ApiResponse<>(null, "User not found"));
        }
    }
    

    Controller remains simple:

    @GetMapping("/{id}")
    public ApiResponse<User> getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
    

    5. Spring's ResponseStatusException

    Throw a Spring-specific exception (keeps domain clean but not fully explicit).

    @Service
    public class UserService {
        public User findById(Long id) {
            return userRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(
                    HttpStatus.NOT_FOUND, "User not found"
                ));
        }
    }
    

    Controller doesn't need special handling; Spring converts it to HTTP 404 automatically.


    Comparison Table

    ApproachDomain PurityExplicit Error InfoBoilerplate
    Result PatternHighYes (enum/class)Medium
    OptionalHighNoLow
    Either (Vavr)HighYesMedium
    Response DTOMediumYesHigh
    ResponseStatusExceptionHighestImplicit (HTTP codes)Low

    When to use each:

    • Result Pattern: Complex business logic, explicit error handling required.
    • Optional: Simple "not found" cases.
    • Either: If you're comfortable with functional programming.
    • Response DTO: When frontend expects standardized format.
    • ResponseStatusException: Rapid prototyping or simple REST APIs.

    For most enterprise applications, I'd recommend the Result Pattern as it balances explicitness, maintainability, and domain purity. What do you think?

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