Skip to content

Instantly share code, notes, and snippets.

@nilshartmann
Created August 28, 2022 07:09
Show Gist options
  • Save nilshartmann/bc5f9b313d00a37b4fc69dbe3c661e45 to your computer and use it in GitHub Desktop.
Save nilshartmann/bc5f9b313d00a37b4fc69dbe3c661e45 to your computer and use it in GitHub Desktop.
abstract class BaseError {
  private final String message;
  
  public BaseError(String message) { this.message = message; }
  
  public String getMessage() { return this.message; }
}

public class InvalidInputError extends BaseError { public InvalidInputError(String message) { super(message); } }
public class NotFoundError extends BaseError { public NotFoundError(String message) { super(message); } }
// ...
@paulbuechner
Copy link

GraphQL Schema:

type Book { ... }

interface BaseError {
    message: String!
}

type NotFoundError implements BaseError {
    message: String!
}

union BookResult = Book | NotFoundError

type Query {
    bookById(id: ID!): BookResult!
}

Java Design:

public interface BookResult { }

public class Book implements BookResult { ... }

public abstract class BaseError implements BookResult { ... }

public class NotFoundError extends BaseError { ... }


public Mono<BookResult> findById(Integer id) {

      log.info("Loading Book with id {} from database.", id);

      final String errorMessage = String.format("There is no Book with id %d", id);

      return this.bookRepository.findById(id)
          .flatMap(Mono::<BookResult>just)
          .switchIfEmpty((Mono.defer(() -> Mono.just(new NotFoundError(errorMessage)))));
  }

@nilshartmann
Copy link
Author

/** BaseError ist allgemein, kennt keine konkreten Error-Typen oder Ergebnisse */
public abstract class BaseError { ... }


public interface BookResult { }

public class Book implements BookResult { ... }


public class NotFoundError extends BaseError implements BookResult { ... }

Im Grunde könntest Du wohl auch auf BookResult verzichten und in findById einfach Object zurückliefern:

public class Book  { ... }
public class NotFoundError extends BaseError  { ... }

public Mono<Object> findById(Integer id) {
  // ...
}

Würde etwas Code sparen, aber dein Ansatz ist dafür expliziter, was ja auch nicht schlecht ist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment