fankao / eStore

Sample Ecommerce application to practice Modern API Specification and Microservices with Spring Boot inspired on https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot
0 stars 0 forks source link

Implementing the OAS code interfaces #2

Closed fankao closed 2 years ago

fankao commented 2 years ago

We just need to create a class for each of the AOS API interfaces and implement it

fankao commented 2 years ago

We'll create CartController.java in the com.packt.modern.api.controllers package and implement CartApi:

@RestController
public class CartController implements CartApi {
    private static final Logger log = LoggerFactory.getLogger(CartsController.class);

    @Override
    public ResponseEntity<List<Item>> addCartItemsByCustomerId(String customerId, @Valid Item item) {
        log.info("Request for customer ID: {}\nItem: {}",
                customerId, item);
        return ok(Collections.EMPTY_LIST);
    }

    @Override
    public ResponseEntity<List<Cart>> getCartByCustomerId(String
                                                                  customerId) {
        throw new RuntimeException("Manual Exception thrown");
    }
    // Other method implementations (omitted)
}
fankao commented 2 years ago

Adding a Global Exception Handler

  1. Let's first write the Error class in the exceptions package that contains all the error information: https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot/blob/main/Chapter03/src/main/java/com/packt/modern/api/exceptions/Error.java
  2. we'll write an enum called ErrorCode that will contain all the exception keys, including user-defined errors and their respective error codes:https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot/blob/main/Chapter03/src/main/java/com/packt/modern/api/exceptions/ErrorCode.java
  3. we'll add a utility to create the Error object: https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot/blob/main/Chapter03/src/main/java/com/packt/modern/api/exceptions/ErrorUtils.java
  4. we'll create a class for implementing the Global Exception Handler: https://github.com/PacktPublishing/Modern-API-Development-with-Spring-and-Spring-Boot/blob/main/Chapter03/src/main/java/com/packt/modern/api/exceptions/RestApiErrorHandler.java