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

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

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(&quot;/{Id}&quot;)
public ResponseEntity&lt;User&gt;  getUserPath(@RequestParam int Id) {

	User user = userRepository.findById(Id).get();
    if (user==null){
        return new ResponseEntity(&quot;Please provide a valid user ID&quot;, HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity&lt;User&gt;(user, HttpStatus.FOUND);
}

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:

确定