0

我正在使用 Spring Boot 构建一个 RESTful API,但是当我尝试处理有关请求的错误时遇到了问题。

GetUserById(代码):

 @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") int idUser) throws UserIntrouvaleException {
        User userFind =  service.getUserById(idUser);
        if(userFind == null){
            throw new UserIntrouvaleException("The user with the ID "+idUser+"does not exist !");
        }
        return userFind;
    }

UserIntrouvaleException(代码):

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserIntrouvaleException extends RuntimeException {
    public UserIntrouvaleException(String s) {
        super(s);
    }
}

错误 :

java.util.NoSuchElementException: No value present
    at java.base/java.util.Optional.get(Optional.java:148) ~[na:na]
    at dashboard.project.service.UserServiceImpl.getUserById(UserServiceImpl.java:33) ~[main/:na]
    at dashboard.project.controller.ApiRestController.getUserById(ApiRestController.java:32) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807) ~[spring-webmvc-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061) ~[spring-webmvc-5.3.1.jar:5.3.1]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961) ~[spring-webmvc-5.3.1.jar:5.3.1]

4

1 回答 1

0

使用 Optional 时,尝试使用 optional.isPresent() 检查返回的可选项是否有任何值,然后对可选项执行任何操作。

如果您可以在 service.getUserById() 中添加逻辑将会很有帮助

于 2020-12-12T00:50:15.050 回答