spring引导api restful:请求的错误处理问题

o7jaxewo  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(391)

我正在用springboot构建一个restfulapi,但是当我试图处理与请求有关的错误时遇到了一个问题。
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]
f45qwnt8

f45qwnt81#

使用optional时,请尝试使用optional.ispresent()检查optional返回的值是否有任何值,然后对optional执行任何操作。
如果您可以在service.getuserbyid()中添加逻辑,将会很有帮助

相关问题