how do we handle duplicate key exception
ashishsoni opened this issue · 1 comments
ashishsoni commented
hi , would it be possible to show an example how we can handle exception raised for example DuplicateKeyException
callicoder commented
Hi Ashish,
You can handle exceptions with Spring-Webflux in the same way you handle exceptions in Spring MVC.
You can use an @ExceptionHandler in the controller to handle exceptions thrown in that controller or you can use a @ControllerAdvice to handle exceptions globally. -
The example below shows how to use @ExceptionHandler -
// Custom Exception
package com.example.webfluxdemo.exception;
public class TweetNotFoundException extends RuntimeException {
public TweetNotFoundException(String tweetId) {
super("Tweet not found with id " + tweetId);
}
}// The Controller Method which throws an exception if tweet was not found with the given id
@GetMapping("/tweets/{id}")
public Mono<Tweet> getTweetById(@PathVariable(value = "id") String tweetId) {
return tweetRepository.findById(tweetId)
.switchIfEmpty(Mono.error(new TweetNotFoundException(tweetId)));
}// Exception Handler Method
@ExceptionHandler
public ResponseEntity handleNotFoundException(TweetNotFoundException ex) {
return ResponseEntity.notFound().build();
}Similarly, If the createTweet() endpoint throws DataIntegrityViolationException, then you can use an exception handler like this -
@ExceptionHandler
public ResponseEntity handleDuplicateKeyException(DuplicateKeyException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}I've added these examples in the repository as well.