内部服务器错误的Post请求Spring Boot [Java]

huangapple go评论58阅读模式
英文:

Internal Server Error on Post Request Spring Boot [Java]

问题

抱歉,我无法完成您的请求。

英文:

I am trying to send a post request to add an User object to the list of users (no database).
getUser, getAllUsers Api endpoints are working fine and giving desired results.

When I send a Post request with User, it is always giving 500 Internal Server Error.

I have also printed out the User and data is fine.

Below is my code -

User Entity (User.java) -

public class User {

	
	private Integer userId;
	
	private String name;
	private String email;
	
	private Account account;

Getters and Setters along with constructors are also there.

My User Service and its implementation -

UserService.java -

@Service
public interface UserService {
	public User getUser(Integer userId);
	public List<User> getAllUsers();
	<T> ResponseEntity<T> deleteUser(Integer userId);
	<T> ResponseEntity<User> addUser(User user);
	
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService{
	List<User> userList = List.of(
			new User(1311, "Vaibhav Shrivastava", "innomightmail@gmail.com"),
			new User(1312, "Varun Shrivastava", "varun@gmail.com"),
			new User(1313, "Rajesh Shrivastava", "rajesh@gmail.com")
		);
	
	@Override
	public User getUser(Integer id) {
		// TODO Auto-generated method stub
		System.out.println(this.userList.stream().filter(user -> user.getUserId().equals(id)).findAny().orElse(null));
		return this.userList.stream().filter(user -> user.getUserId().equals(id)).findAny().orElse(null);
	}

	@Override
	public List<User> getAllUsers() {
		// TODO Auto-generated method stub
		return userList;
	}

	
	@Override
	public <T> ResponseEntity<User> addUser(User user) {
		// TODO Auto-generated method stub
		
		userList.add(user);
		return new ResponseEntity<User>((User)user, HttpStatus.OK);
		
	}

Controller (UserController.java) -

@RestController
@RequestMapping("/user")
public class UserController {
	
@Autowired
private UserService userService;

@Autowired
private RestTemplate restTemplate;

@GetMapping("/{userId}")
public User getUser(@PathVariable("userId") Integer userId) {
	User user = this.userService.getUser(userId);
	Account account = this.restTemplate.getForObject("http://account-service/account/user/" + user.getUserId(), Account.class);
	
	user.setAccount(account);
	
	return user;
	
}

@GetMapping("/all-users")
public List<User> getAllUsers(){
	return this.userService.getAllUsers();
}

@PostMapping("/add-user")
public ResponseEntity<Object> addUser(@RequestBody User user) {
	try {
		  User newUser = new User(user.getUserId(), user.getName(), user.getEmail());
	      this.userService.addUser(newUser);
	      return new ResponseEntity<>(user, HttpStatus.CREATED);
	    } catch (Exception e) {
	      User newUser = new User(user.getUserId(), user.getName(), user.getEmail());
	      return new ResponseEntity<>(newUser, HttpStatus.INTERNAL_SERVER_ERROR);
	    }
	
}

getUser and getAllUsers are working fine (dont get confused by account in getUser that is my another microservice)

When I am sending Post request using postman -

{
    "userId": 1314,
    "name": "James",
    "email": "james@gmail.com"
}

I am getting response -
500 Internal server error and User object which I wanted to check so I printed it out -

{
    "userId": 1314,
    "name": "Kavita Shrivastava",
    "email": "kavita@gmail.com",
    "account": null
}

I do not know why I am getting Internal server error.

The request should add the new User to the list in UserServiceImpl.

答案1

得分: 2

堆栈跟踪包含您正在寻找的所有信息。 UserServiceImple.addUser 尝试向 userList 添加一个对象。但 userList 是一个不可变列表,所以它引发异常。代码流程到 "catch" 块,然后返回 500,同时返回新创建的对象。

英文:

Stack trace has all the information you are looking for. UserServiceImple.addUser tries to add an object to the userList . but userList is an immutable list. so it throws exception. code flows to "catch" block and it returns 500 with newly created object.

答案2

得分: 1

根据我的看法,这是因为当你使用List.of时,它等同于Collections.unmodifiableList,因此如果尝试修改它,会引发异常,因为它是不可变的。

英文:

In my opinion That's happens because
when U use List.of it equals to
Collections.unmodifiableList so it will throw an exception as Its Immutable.

huangapple
  • 本文由 发表于 2023年2月16日 18:09:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定