当返回类型为对象时,在REST服务中返回一个字符串。

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

Returning a string when the return type is an object in a REST service

问题

  1. @GetMapping("/{Id}")
  2. public @ResponseBody User getUserPath(@PathVariable int Id) {
  3. User user = userRepository.findById(Id).orElse(null);
  4. if (user == null) {
  5. // return "Please provide a valid user ID";
  6. throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Please provide a valid user ID");
  7. }
  8. return user;
  9. }
英文:

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:

  1. @GetMapping("/{Id}")
  2. public @ResponseBody User getUserPath(@PathVariable int Id) {
  3. User user = userRepository.findById(Id).get();
  4. if (user==null){
  5. //return "Please provide a valid user ID"
  6. }
  7. return user;
  8. }

Does somebody know how to do this?

答案1

得分: 0

  1. 简单地返回对象
  2. `public @ResponseBody Object getUserPath()`
  3. **更新 1**
  4. 在这种情况下,我认为更好的做法是抛出异常,使用 `@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状态代码。

  1. @GetMapping("/{Id}")
  2. public ResponseEntity<User> getUserPath(@RequestParam int Id) {
  3. User user = userRepository.findById(Id).get();
  4. if (user == null) {
  5. return new ResponseEntity("Please provide a valid user ID", HttpStatus.NOT_FOUND);
  6. }
  7. return new ResponseEntity<User>(user, HttpStatus.FOUND);
  8. }
英文:

Below code will do your job. This will return your custom string and the correct HTTP status code as well.

  1. @GetMapping(&quot;/{Id}&quot;)
  2. public ResponseEntity&lt;User&gt; getUserPath(@RequestParam int Id) {
  3. User user = userRepository.findById(Id).get();
  4. if (user==null){
  5. return new ResponseEntity(&quot;Please provide a valid user ID&quot;, HttpStatus.NOT_FOUND);
  6. }
  7. return new ResponseEntity&lt;User&gt;(user, HttpStatus.FOUND);
  8. }

huangapple
  • 本文由 发表于 2020年9月23日 18:52:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64026352.html
匿名

发表评论

匿名网友

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

确定