[英]Different return types for function Java
I'm using Spring Boot with Data JPA. 我正在将Spring Boot与Data JPA一起使用。
I have the following code. 我有以下代码。
A User Class with name and an informative message. 具有名称和提示消息的用户类。
class UserResponse{
private String name;
private String message;
}
User JPA Repository which finds userBy id; 用户JPA信息库,可找到userBy ID;
interface UserRepository{
Optional<User> findUserById(String id);
}
User Service which invokes repo and set message if user not found 用户服务,如果找不到用户,则调用回购并设置消息
class UserService(){
UserResponse user = new UserResponse();
public UserResponse getUserById(String userId){
Optional<User> useroptional = userRepository.findById(userId);
if(userOptional.isPresent()){
user.setName(userOptional.get().getName());
}else{
user.setMessage("User Not Found");
}
}
UserController has to set proper HTTP status code as per the message. UserController必须根据消息设置适当的HTTP状态代码。
class UserController(){
public ResponseEntity<UserResponse> getUserById(String id){
UserResponse user = userService.getUserById(id);
HttpStatus status = OK;
if(!StringUtils.isEmpty(user.getMessage())){
status = NOT_FOUND;
}
return new ResponseEntity<>(user,status);
}
}
The problems I have faced is inorder to set proper status code in controller layer I have to inspect user message,which i didn't like. 我遇到的问题是为了在控制器层中设置适当的状态代码,我必须检查用户消息,这是我不喜欢的。 Is there anyway we can create a control flow for Success and Failure cases.
无论如何,我们可以为成功和失败案例创建控制流。
Say One Return type and flow for Success scenario and vice-versa. 对成功场景说一种返回类型和流程,反之亦然。 I know Scala has this feature with Either keyword.
我知道Scala具有Either关键字的此功能。 Is there any alternate in Java ?
Java中有其他替代方法吗? Or any other approach I can use to handle this better...
或我可以用来更好地处理此问题的任何其他方法...
One approach would be returning RepsonseEntity in service layer itself with proper status code but setting status code is controller's Responsibility is what I felt. 一种方法是使用适当的状态代码在服务层本身中返回RepsonseEntity,但是设置状态代码是控制器的责任感。
In case of failure you can throw custom Exception
with proper message. 如果失败,您可以使用适当的消息引发自定义
Exception
。 Then you can catch it in @ControllerAdvice
. 然后,您可以在
@ControllerAdvice
捕获它。 I'll add an example in a moment. 我将在稍后添加一个示例。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<String> exception(MyCustomException e) {
return new ResponseEntity(e.getMessage(), HttpStatus.NotFound);
}
}
In one @ControllerAdvice
one could have more methods listening for different Exception
s. 在一个
@ControllerAdvice
可以有更多的方法侦听不同的Exception
。 Custom Exception can hold whatever you want - it's a normal class - so you can return ResponseEntity
of whatever you want. Custom Exception可以容纳任何您想要的东西-这是一个普通的类-因此您可以返回任何想要的
ResponseEntity
。
For example: 例如:
@Transactional(readOnly = true)
@GetMapping("/{id}")
public ResponseEntity<?> getUserById(@PathVariable("id") String userId) {
return userRepository.findById(userId)
.map(user -> ResponseEntity.ok().body(user))
.orElse(new ResponseEntity<>(/* new ErrorMessage */, HttpStatus.NOT_FOUND))
}
For 'not found' response you have to create an error message object and return it to client. 对于“未找到”响应,您必须创建一个错误消息对象并将其返回给客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.