What to do if a don't want to throw domain exception?
- User
What to do if a don't want to throw domain exception?
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
Resultobject 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
Optionalcan 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
EitherInspired 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
ResponseStatusExceptionThrow 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
Approach Domain Purity Explicit Error Info Boilerplate Result Pattern High Yes (enum/class) Medium Optional High No Low Either (Vavr) High Yes Medium Response DTO Medium Yes High ResponseStatusException Highest Implicit (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?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.