ApiController.java

  1. package edu.ucsb.cs156.happiercows.controllers;

  2. import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
  3. import edu.ucsb.cs156.happiercows.errors.NoCowsException;
  4. import edu.ucsb.cs156.happiercows.errors.NotEnoughMoneyException;
  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import edu.ucsb.cs156.happiercows.models.CurrentUser;
  7. import edu.ucsb.cs156.happiercows.services.CurrentUserService;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.web.bind.annotation.ExceptionHandler;
  10. import org.springframework.web.bind.annotation.ResponseStatus;

  11. import java.util.Map;

  12. public abstract class ApiController {
  13.   @Autowired
  14.   private CurrentUserService currentUserService;

  15.   protected CurrentUser getCurrentUser() {
  16.     return currentUserService.getCurrentUser();
  17.   }
  18.  
  19.   protected Object genericMessage(String message) {
  20.     return Map.of("message", message);
  21.   }

  22.   @ExceptionHandler({ EntityNotFoundException.class })
  23.   @ResponseStatus(HttpStatus.NOT_FOUND)
  24.   public Object handleGenericException(Throwable e) {
  25.     return Map.of(
  26.       "type", e.getClass().getSimpleName(),
  27.       "message", e.getMessage()
  28.     );
  29.   }

  30.   @ExceptionHandler({ NoCowsException.class, NotEnoughMoneyException.class})
  31.   @ResponseStatus(HttpStatus.BAD_REQUEST)
  32.   public Object handleBadRequest(Throwable e) {
  33.     return Map.of(
  34.       "type", e.getClass().getSimpleName(),
  35.       "message", e.getMessage()
  36.     );
  37.   }
  38. }