ResponseEntity Spring MVC

时间:2014-07-16 17:59:50

标签: rest spring-mvc

使用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);
    }
}

1 个答案:

答案 0 :(得分:4)

我意识到您具体询问了如何使用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 {
    // ...
}