File tree Expand file tree Collapse file tree 3 files changed +21
-6
lines changed
src/main/java/org/kunicki/functional_java Expand file tree Collapse file tree 3 files changed +21
-6
lines changed Original file line number Diff line number Diff line change 11package org .kunicki .functional_java .api ;
22
3- import org .kunicki .functional_java .common .Attempt ;
3+ import org .kunicki .functional_java .common .Or ;
44import org .kunicki .functional_java .domain .Service ;
55import org .kunicki .functional_java .domain .User ;
6+ import org .kunicki .functional_java .domain .error .Error ;
7+ import org .kunicki .functional_java .domain .error .ExternalError ;
68
79import java .util .Optional ;
810
@@ -37,11 +39,15 @@ public Response<?> findUserById(Long id) {
3739 }
3840
3941 public Response <?> betterFindUserById (Long id ) {
40- final var user = Attempt . of (() -> service .findUserById (id ) );
42+ final var user = service .betterFindUserById (id );
4143 return switch (user ) {
42- case Attempt .Success <Optional <User >> success ->
43- success .value ().map (Response ::ok ).orElse (Response .notFound ());
44- case Attempt .Failure <?> failure -> Response .serverError (failure .e ().getMessage ());
44+ case Or .Right <?, Optional <User >> r -> r .value ().map (Response ::ok ).orElse (Response .notFound ());
45+ case Or .Left <Error , ?> l -> switch (l .value ()) {
46+ case Error .DomainError e && e .message ().startsWith ("E" ) ->
47+ Response .serverError ("Specific domain error: " + e .message ());
48+ case Error .DomainError e -> Response .serverError ("Domain error: " + e .message ());
49+ case ExternalError e -> Response .serverError ("External error: " + e .message ());
50+ };
4551 };
4652 }
4753}
Original file line number Diff line number Diff line change 11package org .kunicki .functional_java .domain ;
22
3+ import org .kunicki .functional_java .common .Or ;
4+ import org .kunicki .functional_java .domain .error .Error ;
5+
36import java .util .Optional ;
47
58public class Service {
@@ -55,6 +58,10 @@ public Optional<User> findUserById(Long id) {
5558 return Optional .of (new User (42L , "Jacek" ));
5659 }
5760
61+ public Or <Error , Optional <User >> betterFindUserById (Long id ) {
62+ return Or .left (new Error .DomainError ("Boom!" ));
63+ }
64+
5865 //region Tips
5966 /*
6067 T: Return expected errors as plain values
Original file line number Diff line number Diff line change 11package org .kunicki .functional_java .domain .error ;
22
3- public interface Error {
3+ public sealed interface Error permits Error . DomainError , ExternalError {
44
5+ record DomainError (String message ) implements Error {
6+ }
57}
You can’t perform that action at this time.
0 commit comments