[英]How to handle null return value in spring boot
我有一个关于 spring 引导的问题。 当我想从我的数据库中获取特定用户时,一切正常,但我该如何处理 null 响应(没有这样的用户)? 我想将 null 的返回值作为 ResponseEntity 处理,但是当有具有该 ID 的用户时,我需要返回用户详细信息。 所以我无法将返回值设置为 ResponseEntity。 这是问题的屏幕截图:
这是代码:
@GetMapping("get/{id}")
public User findById(@PathVariable int id) throws Exception {
try {
if(userMapper.findById(id) != null) {
return userMapper.findById(id);
}else {
throw new Exception("YOK ULAN YOK");
}
}catch (Exception e) {
// TODO: Make perfect
return new User(-1);
}
}
这是返回值:
{
"email": null,
"username": null,
"password": null,
"name": null,
"surname": null,
"age": 0,
"photoLink": null,
"dateOfBirth": null,
"phoneNumber": null,
"city": null,
"country": null,
"friendList": null,
"plan": null,
"id": -1,
"planned": false
}
我不想发送 -1 用户,我想发送未找到用户的响应。 我该如何处理?
谢谢,
最好的方法是将方法返回类型从User
更改为ResponseEntity<?>
,smth。 喜欢:
@GetMapping("get/{id}")
public ResponseEntity<?> findById(@PathVariable int id) throws Exception {
User user = userMapper.findById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
或使用可选:
@GetMapping("get/{id}")
public ResponseEntity<?> findById(@PathVariable int id) throws Exception {
return Optional.ofNullable(userMapper.findById(id))
.map(ResponseEntity::ok)
.orElseGet(ResponseEntity.notFound()::build);
}
我们可以尝试定义一个带有响应状态的异常。
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
然后,在你的 controller 中,抛出这个异常
throw new ResourceNotFoundException()
或者,直接设置Response
的状态。
顺便说一句,更好的方法是定义我们的业务代码来实现它。
您可以使用异常处理程序来处理这些类型的异常。 要完成这项工作,您可以首先返回Optional<User>
而不是User
。 然后你可以写你的 controller 如下。
@GetMapping(value = "/get/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> findById(@PathVariable int id) {
return ResponseEntity
.status(HttpStatus.OK)
.body(userMapper.findById(id)
.orElseThrow(UserNotFoundException::new);
}
UserNotFoundException
是自定义 class。 您可以从RuntimeException
扩展,这样异常就不会被选中。
public class UserNotFoundException extends RuntimeException {}
然后你可以做一个错误响应ErrorResponse
。 您可以自由添加您喜欢的字段,但它可能如下所示:
@Getter
@Setter
public class ErrorResponse {
private int code;
private String description;
}
然后,您可以在ExceptionHandler
中处理此UserNotFoundException
:
@RestControllerAdvice
@Slf4j
public class ApplicationNameExceptionHandler {
@ExceptionHandler
public ResponseEntity<ErrorResponse> handleException(UserNotFoundException e) {
log.info("User not found");
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(HttpStatus.NOT_FOUND.value());
errorResponse.setDescription("User not found");
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.body(errorResponse);
}
这种方法的优点是您可以保持控制器简洁和整洁,并且所有 controller 异常都可以在同一个 class ( ApplicationNameExceptionHandler
) 中处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.