Handling Exceptions in RESTful User Responses
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
// Method to retrieve a book by its ID
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
Book book = bookService.findBookById(id)
.orElseThrow(() -> new BookNotFoundException("Book with ID: " + id + " not found."));
return new ResponseEntity<>(book, HttpStatus.OK);
}
// Exception handler for BookNotFoundException
@ExceptionHandler(BookNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleBookNotFoundException(BookNotFoundException ex) {
// Log the exception details for debugging
Logger.log(ex.getMessage());
// Return a user-friendly message and the appropriate HTTP status
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("Book not found. Please check the provided book ID.");
}
// ... other methods or exception handlers ...
}PreviousJWT Authentication and Role-Based Authorization with Java Spring BootNextGlobal REST Error Responses via @ControllerAdvice
Last updated