Getting 500 error instead of 400 and 409
I am tryna handle the erros in the Api and Return the Exception according to the need as u can see in the code but i am not getting proper errors as i return them !
@Override
public Optional<BooksDetails> addBooks(BooksDetailsDto booksDetailsDto, Long roll_no) {
Optional<StudentDetails> studentObj = detailsRepository.findById(roll_no);
Optional<BooksDetails> existingBook = bookDetailsRepository.findByBookId(booksDetailsDto.getBookId());
if (!studentObj.isPresent()) {
throw new StudentNotFound("No Student Has been Founded with this roll_no");
}
if (existingBook.isPresent()) {
throw new BookAlreadyExist("This Book is Already Present");
}
BooksDetails booksDetails = BookDetailsDtoMapper.toEntity(booksDetailsDto, studentObj.get(),
apiService);
BooksDetails savedBook = bookDetailsRepository.save(booksDetails);
return Optional.of(savedBook);
}@Override
public Optional<BooksDetails> addBooks(BooksDetailsDto booksDetailsDto, Long roll_no) {
Optional<StudentDetails> studentObj = detailsRepository.findById(roll_no);
Optional<BooksDetails> existingBook = bookDetailsRepository.findByBookId(booksDetailsDto.getBookId());
if (!studentObj.isPresent()) {
throw new StudentNotFound("No Student Has been Founded with this roll_no");
}
if (existingBook.isPresent()) {
throw new BookAlreadyExist("This Book is Already Present");
}
BooksDetails booksDetails = BookDetailsDtoMapper.toEntity(booksDetailsDto, studentObj.get(),
apiService);
BooksDetails savedBook = bookDetailsRepository.save(booksDetails);
return Optional.of(savedBook);
}@PostMapping("/addBook/{roll_no}")
public ResponseEntity<?> addBooksToStudent(@RequestBody BooksDetailsDto booksDetailsDto,
@PathVariable Long roll_no) {
Optional<BooksDetails> studentBook = detailsService.addBooks(booksDetailsDto, roll_no);
if (studentBook.isPresent()) {
return ResponseEntity.ok(studentBook.get()); // Return the added book
} else {
return ResponseEntity.badRequest().build(); // Return a 400 Bad Request if the book could not be added
}
}@PostMapping("/addBook/{roll_no}")
public ResponseEntity<?> addBooksToStudent(@RequestBody BooksDetailsDto booksDetailsDto,
@PathVariable Long roll_no) {
Optional<BooksDetails> studentBook = detailsService.addBooks(booksDetailsDto, roll_no);
if (studentBook.isPresent()) {
return ResponseEntity.ok(studentBook.get()); // Return the added book
} else {
return ResponseEntity.badRequest().build(); // Return a 400 Bad Request if the book could not be added
}
}