gpt4 book ai didi

rest - Spring MVC 响应实体

转载 作者:行者123 更新时间:2023-12-02 05:52:29 26 4
gpt4 key购买 nike

使用 ReponseEntity 返回错误消息的最佳方式是什么?

假设我有以下方法

@Transactional
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable("id") Long id) {

User user = userRepository.findOne(id);

if (user == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
else {
return new ResponseEntity<>(user, HttpStatus.OK);
}

现在如果我想向前端返回错误信息怎么办?我无法执行以下操作,因为方法返回类型是

ResponseEntity<User> 

不是

ResponseEntity<String>

所以这行不通

    if (user == null) {
return new ResponseEntity<>("User does not exist", HttpStatus.NOT_FOUND);
}

我可以使方法返回类型

 ResponseEntity<Object> 

但这似乎是草率且糟糕的做法。我希望能够至少返回一条简短的错误消息,该消息向前端提供一些错误指示。执行此操作的最佳方法是什么?

更新:

经过一番挖掘后,我想出了这个,它似乎有效,但很好奇它是否会对性能产生影响。

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getUser(@PathVariable("id") Long id) {

User user = userRepository.findOne(id);

if (user == null) {
return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
}
else {
return new ResponseEntity<>(user, HttpStatus.OK);
}
}

最佳答案

我知道您具体询问了有关使用 ReponseEntity 返回错误消息的问题,但您也可以考虑使用 Spring MVCs exception handling达到相同的结果:

// Example from the linked Spring article:

@RequestMapping(value="/orders/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Order order = orderRepository.findOrderById(id);
if (order == null) throw new OrderNotFoundException(id);
model.addAttribute(order);
return "orderDetail";
}


@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order") // 404
public class OrderNotFoundException extends RuntimeException {
// ...
}

关于rest - Spring MVC 响应实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24787612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com