BAEL-7540

This commit is contained in:
reza ganji 2024-03-30 13:13:45 +03:30
parent 7c93d40044
commit 0b1672898e
4 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.webflux.exceptionhandeling.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.webflux.exceptionhandeling.ex.NotFoundException;
import com.baeldung.webflux.exceptionhandeling.repository.UserRepository;
import com.baeldung.webflux.zipwhen.model.User;
import reactor.core.publisher.Mono;
@RestController
public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/user/{id}")
public Mono<User> getUserByIdThrowingException(@PathVariable String id) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(new NotFoundException("User not found")));
}
@GetMapping("/user/{id}")
public Mono<User> getUserByIdUsingMonoError(@PathVariable String id) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(() -> new NotFoundException("User not found")));
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.webflux.exceptionhandeling.ex;
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.webflux.exceptionhandeling.model;
public class User {
private String id;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User(String userId, String userName) {
this.id=userId;
this.username=userName;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.webflux.exceptionhandeling.repository;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Repository;
import com.baeldung.webflux.zipwhen.model.User;
import reactor.core.publisher.Mono;
@Repository
public class UserRepository {
private final Map<String, User> userDatabase = new ConcurrentHashMap<>();
public UserRepository() {
userDatabase.put("1", new User("1", "John Doe"));
userDatabase.put("2", new User("2", "Jane Smith"));
}
public Mono<User> findById(String id) {
return Mono.justOrEmpty(userDatabase.get(id));
}
}