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
}

}
27 Replies
JavaBot
JavaBot5mo ago
This post has been reserved for your question.
Hey @Danix! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Danix
DanixOP5mo ago
Handling Both of them here
@ExceptionHandler(StudentNotFound.class)
public ResponseEntity<Map<String, String>> handleStudentNotFoundException(StudentNotFound exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(errorMap);
}

@ExceptionHandler(BookAlreadyExist.class)
public ResponseEntity<Map<String, String>> handleBookAlreadyExistException(BookAlreadyExist exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(errorMap);
}
@ExceptionHandler(StudentNotFound.class)
public ResponseEntity<Map<String, String>> handleStudentNotFoundException(StudentNotFound exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(errorMap);
}

@ExceptionHandler(BookAlreadyExist.class)
public ResponseEntity<Map<String, String>> handleBookAlreadyExistException(BookAlreadyExist exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(errorMap);
}
and getting 500 internal error for this why ? can someone help
Koblížkáč
Koblížkáč5mo ago
is there any error in logs?
Danix
DanixOP5mo ago
yehh the same 500 error with the same name exception that i have made !
Koblížkáč
Koblížkáč5mo ago
can you debug it so you know on what ĺine its happening?
Danix
DanixOP5mo ago
Hm yeh sure I will try
dan1st
dan1st5mo ago
Is this declared in the same controller, an @ControllerAdvice or similar? Can you show that?
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Danix
DanixOP5mo ago
I have made a different class for it and annotated it with the @RestControllerAdvice .. I will show u the code after reaching home
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(StudentNotFound.class)
public ResponseEntity<Map<String, String>> handleStudentNotFoundException(StudentNotFound exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(errorMap);
}

@ExceptionHandler(BookAlreadyExist.class)
public ResponseEntity<Map<String, String>> handleBookAlreadyExistException(BookAlreadyExist exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(errorMap);
}}
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(StudentNotFound.class)
public ResponseEntity<Map<String, String>> handleStudentNotFoundException(StudentNotFound exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(errorMap);
}

@ExceptionHandler(BookAlreadyExist.class)
public ResponseEntity<Map<String, String>> handleBookAlreadyExistException(BookAlreadyExist exception) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(errorMap);
}}
@dan1st | Daniel
dan1st
dan1st5mo ago
Is the exception thrown from a RestController?
Danix
DanixOP5mo ago
No from the service class method ..
dan1st
dan1st5mo ago
what calls the service method? A RestController? Another controller? Is the exception rethrown anywhere? Can you show the complete stack trace?
Danix
DanixOP5mo ago
A RestController as u can see in the code as well yehh sure
dan1st
dan1st5mo ago
I just see the endpoint method, not the whole controller class I don't know whether it's an @Controller or @RestController
Danix
DanixOP5mo ago
Danix
DanixOP5mo ago
@RestController
@RequestMapping("/api/Student")
@CrossOrigin(origins = "http://localhost:3000")
public class RestApplication {

@Autowired
private StudentDetailsService detailsService;
@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
}

}
}
@RestController
@RequestMapping("/api/Student")
@CrossOrigin(origins = "http://localhost:3000")
public class RestApplication {

@Autowired
private StudentDetailsService detailsService;
@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
}

}
}
dan1st
dan1st5mo ago
What's the package of your RestControllerAdvice? What's the package of your main/application class?
Danix
DanixOP5mo ago
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
dan1st
dan1st5mo ago
I meant of the class you annotated with RestControllerAdvice the GlobalExceptionHandler
Danix
DanixOP5mo ago
package com.ShelfSpace.ShelfSpace;
package com.ShelfSpace.ShelfSpace;
dan1st
dan1st5mo ago
Is that one actually instantiated and managed by Spring? What's the package of that?
Danix
DanixOP5mo ago
package com.ShelfSpace.advice;
package com.ShelfSpace.advice;
dan1st
dan1st5mo ago
ohhh yes that's the problem So your main class is in com.ShelfSpace.ShelfSpace This means Spring will only look at com.ShelfSpace.ShelfSpace and subpackages so it won't look at anything in com.ShelfSpace.advice Also fix your package names
Danix
DanixOP5mo ago
hmm got it ok thanks
JavaBot
JavaBot5mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Danix
DanixOP5mo ago
buddy
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?