@@ -35,9 +35,10 @@ public Mono<Tweet> createTweets(@Valid @RequestBody Tweet tweet) {
3535 }
3636
3737 @ GetMapping ("/tweets/{id}" )
38-  public  Mono <Tweet > getTweetById (@ PathVariable (value  = "id" ) String  tweetId ) {
38+  public  Mono <ResponseEntity < Tweet > > getTweetById (@ PathVariable (value  = "id" ) String  tweetId ) {
3939 return  tweetRepository .findById (tweetId )
40-  .switchIfEmpty (Mono .error (new  TweetNotFoundException (tweetId )));
40+  .map (savedTweet  -> ResponseEntity .ok (savedTweet ))
41+  .defaultIfEmpty (ResponseEntity .notFound ().build ());
4142 }
4243
4344 @ PutMapping ("/tweets/{id}" )
@@ -70,14 +71,19 @@ public Flux<Tweet> streamAllTweets() {
7071 }
7172
7273
73-  // Exception Handling Examples 
74-  @ ExceptionHandler 
74+ 75+ 76+  /* 
77+  Exception Handling Examples (These can be put into a @ControllerAdvice to handle exceptions globally) 
78+  */ 
79+ 80+  @ ExceptionHandler (DuplicateKeyException .class )
7581 public  ResponseEntity  handleDuplicateKeyException (DuplicateKeyException  ex ) {
7682 return  ResponseEntity .status (HttpStatus .CONFLICT ).body (new  ErrorResponse ("A Tweet with the same text already exists" ));
7783 }
7884
79-  @ ExceptionHandler 
80-  public  ResponseEntity  handleNotFoundException (TweetNotFoundException  ex ) {
85+  @ ExceptionHandler ( TweetNotFoundException . class ) 
86+  public  ResponseEntity  handleTweetNotFoundException (TweetNotFoundException  ex ) {
8187 return  ResponseEntity .notFound ().build ();
8288 }
8389
0 commit comments