File tree Expand file tree Collapse file tree 2 files changed +12
-8
lines changed
src/main/java/com/example/webfluxdemo Expand file tree Collapse file tree 2 files changed +12
-8
lines changed Original file line number Diff line number Diff line change @@ -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
Original file line number Diff line number Diff line change 11package com .example .webfluxdemo .model ;
22
33import org .springframework .data .annotation .Id ;
4- import org .springframework .data .mongodb .core .index .Indexed ;
54import org .springframework .data .mongodb .core .mapping .Document ;
65
76import javax .validation .constraints .NotBlank ;
@@ -20,7 +19,6 @@ public class Tweet {
2019
2120 @ NotBlank
2221 @ Size (max = 140 )
23- @ Indexed (unique = true )
2422 private String text ;
2523
2624 @ NotNull
You can’t perform that action at this time.
0 commit comments