Exception Handling in Spring

Hey i am getting 500 response code instead of 404 even after handling the exception
package com.ShelfSpace.ShelfSpace.exception;

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException() {
super();
}

public ResourceNotFoundException(String message) {
super(message);
}

public ResourceNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
}
package com.ShelfSpace.ShelfSpace.exception;

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException() {
super();
}

public ResourceNotFoundException(String message) {
super(message);
}

public ResourceNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
}
14 Replies
JavaBot
JavaBot6mo 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
DanixOP6mo ago
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(code = HttpStatus.NOT_FOUND) /// If the data is not successfully comeout from the External
/// Api
public Map<String, String> handleResourceNotFoundException(ResourceNotFoundException exception) {

Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return errorMap;
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(code = HttpStatus.NOT_FOUND) /// If the data is not successfully comeout from the External
/// Api
public Map<String, String> handleResourceNotFoundException(ResourceNotFoundException exception) {

Map<String, String> errorMap = new HashMap<>();
errorMap.put("Error", exception.getMessage());
return errorMap;
}
}
@GetMapping("/getAllStudents")
public ResponseEntity<List<StudentDetailsDto>> getAllStudents() {
Optional<List<StudentDetails>> studentDetailsIt = detailsService.getAllStudent();
List<StudentDetailsDto> studentDetailsList = new ArrayList<>();

studentDetailsIt.get().forEach(studentDetails -> {
studentDetailsList.add(StudentDetailsDtoMapper.toDto(studentDetails));
});
return new ResponseEntity<>(studentDetailsList, HttpStatus.OK);

}
@GetMapping("/getAllStudents")
public ResponseEntity<List<StudentDetailsDto>> getAllStudents() {
Optional<List<StudentDetails>> studentDetailsIt = detailsService.getAllStudent();
List<StudentDetailsDto> studentDetailsList = new ArrayList<>();

studentDetailsIt.get().forEach(studentDetails -> {
studentDetailsList.add(StudentDetailsDtoMapper.toDto(studentDetails));
});
return new ResponseEntity<>(studentDetailsList, HttpStatus.OK);

}
@Override
public Optional<List<StudentDetails>> getAllStudent() {
List<StudentDetails> studentDetailsList = detailsRepository.findAll();
if (studentDetailsList.isEmpty()) {
throw new ResourceNotFoundException("No Resource founded");
}
return Optional.of(studentDetailsList);
}
@Override
public Optional<List<StudentDetails>> getAllStudent() {
List<StudentDetails> studentDetailsList = detailsRepository.findAll();
if (studentDetailsList.isEmpty()) {
throw new ResourceNotFoundException("No Resource founded");
}
return Optional.of(studentDetailsList);
}
Peter Rader
Peter Rader6mo ago
Try add the@ResponseStatus(HttpStatus.NOT_FOUND) on the exception-class.
Danix
DanixOP6mo ago
already did it but no changement after that
Peter Rader
Peter Rader6mo ago
Ah ok. What spring version? 4.2?
Danix
DanixOP6mo ago
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
This one
Peter Rader
Peter Rader6mo ago
Ok. Then I need more informations. Please show the stacktrace (obfuscate things you need to hide).
Danix
DanixOP6mo ago
szatkus
szatkus6mo ago
You should return an empty optional if resource is not found and handle it in the controller. Although this code should work there's no reason to add piles of magic.
tjoener
tjoener6mo ago
Hmm, your service handles the business logic, so if you expect to get a value from the database there and you don't have it, that's the place to throw an exception, not in the controller. The controller should handle any unexpected exceptions that come up though, because that's it's task
szatkus
szatkus6mo ago
Doesn't sound like a case for exceptions. Missing value isn't anything exceptional. Although this whole code is a mess. Somehow it returns a list that is packed in Optional...
tjoener
tjoener6mo ago
It is if you actually expect it to be there. But I agree on the second point
Peter Rader
Peter Rader5mo ago
Are you sure? Can you prove it by show the code?
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?