英文:
Returning a string when the return type is an object in a REST service
问题
@GetMapping("/{Id}")
public @ResponseBody User getUserPath(@PathVariable int Id) {
User user = userRepository.findById(Id).orElse(null);
if (user == null) {
// return "Please provide a valid user ID";
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Please provide a valid user ID");
}
return user;
}
英文:
I am creating a REST Service which returns user objects that can be filtered. I use @ResponseBody User when I return a user. But when the id doesn't exist, I want to display a String saying "Please provide a valid user ID". How do I do this when the return type is User?
code:
@GetMapping("/{Id}")
public @ResponseBody User getUserPath(@PathVariable int Id) {
User user = userRepository.findById(Id).get();
if (user==null){
//return "Please provide a valid user ID"
}
return user;
}
Does somebody know how to do this?
答案1
得分: 0
简单地返回对象
`public @ResponseBody Object getUserPath()`
**更新 1**:
在这种情况下,我认为更好的做法是抛出异常,使用 `@ControllerAdvice` + `@ExceptionHandler` 进行处理,并在那里返回错误字符串
英文:
simply return object
public @ResponseBody Object getUserPath()
update 1:
IMHO much better in this case is to throw exception, handle it with @ControllerAdvice
+ @ExceptionHandler
and return error with string there
答案2
得分: 0
以下代码将完成您的工作。这将返回您的自定义字符串和正确的HTTP状态代码。
@GetMapping("/{Id}")
public ResponseEntity<User> getUserPath(@RequestParam int Id) {
User user = userRepository.findById(Id).get();
if (user == null) {
return new ResponseEntity("Please provide a valid user ID", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.FOUND);
}
英文:
Below code will do your job. This will return your custom string and the correct HTTP status code as well.
@GetMapping("/{Id}")
public ResponseEntity<User> getUserPath(@RequestParam int Id) {
User user = userRepository.findById(Id).get();
if (user==null){
return new ResponseEntity("Please provide a valid user ID", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.FOUND);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论