Reputation: 6606
What is the best way to return an error message with ReponseEntity?
Say I have the following method
@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);
}
Now what if I want to return an error message to the front end? I can't do the following because the method return type is
ResponseEntity<User>
not
ResponseEntity<String>
so this will not work
if (user == null) {
return new ResponseEntity<>("User does not exist", HttpStatus.NOT_FOUND);
}
I could make the method return type
ResponseEntity<Object>
but that just seems slopy and bad practice. I want to be able to return at least a brief error message that gives some indication of what went wrong to the front end. How is the best way to go about doing this?
Update:
After some digging around I came up with this and it seems to work but curious if it would have a performance impact.
@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);
}
}
Upvotes: 4
Views: 2980
Reputation: 1394
I realise you asked specifically about returning the error message using ReponseEntity, but you could also consider using Spring MVCs exception handling to acheive the same outcome:
// 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 {
// ...
}
Upvotes: 4