Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring启动连接异常未被捕获_Java_Spring_Spring Boot_Exception_Resttemplate - Fatal编程技术网

Java Spring启动连接异常未被捕获

Java Spring启动连接异常未被捕获,java,spring,spring-boot,exception,resttemplate,Java,Spring,Spring Boot,Exception,Resttemplate,我正在使用RestTemplate连接到另一个服务,我正在捕获一个ConnectException,但是catch块从未捕获它。异常在result=restemplate.getForEntity(uri,String.class)行中抛出,在控制台中我确实得到了以下结果: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native

我正在使用RestTemplate连接到另一个服务,我正在捕获一个ConnectException,但是catch块从未捕获它。异常在result=restemplate.getForEntity(uri,String.class)行中抛出,在控制台中我确实得到了以下结果:

java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method) ~[na:1.8.0_201]
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) ~[na:1.8.0_201]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_201]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_201]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_201]
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_201]
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_201]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_201]
    at java.net.Socket.connect(Socket.java:538) ~[na:1.8.0_201]
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180) ~[na:1.8.0_201]
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) ~[na:1.8.0_201]
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) ~[na:1.8.0_201]
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242) ~[na:1.8.0_201]
    at sun.net.www.http.HttpClient.New(HttpClient.java:339) ~[na:1.8.0_201]
    at sun.net.www.http.HttpClient.New(HttpClient.java:357) ~[na:1.8.0_201]
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220) ~[na:1.8.0_201]
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156) ~[na:1.8.0_201]
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050) ~[na:1.8.0_201]
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984) ~[na:1.8.0_201]
    at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:338) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at com.tdl.controller.ToDoNoteController.addUserToNote(ToDoNoteController.java:323) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]
方法本身:

@PostMapping("/todos/{toDoNoteId}/users")
    public ResponseEntity<?> addUserToNote(@RequestBody User user,@PathVariable int toDoNoteId) throws JsonParseException, JsonMappingException, ConnectException, IOException{
        String email = user.getEmail();
        final String uri = "http://friend:5000/users/"+email;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result =null;
        int statusCode=0;
        ObjectMapper mapper = new ObjectMapper();
        //ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);

        //return null;

        try { // If user exists we will just add it to our ToDoNote

             result = restTemplate.getForEntity(uri, String.class); // exception thrown here

             ResponsePojo pojo = mapper.readValue(result.getBody(), ResponsePojo.class);
             User userToRespond = new User(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
             ToDoNote toDoNote = toDoNoteService.getToDoNoteById(toDoNoteId);
             if(toDoNote.checkIfUserExists(userToRespond)==true) {
                    return new ResponseEntity<String>("\"User already in this note\"",HttpStatus.CONFLICT);
             }
                else {
                    toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
                    return new ResponseEntity<User>(userToRespond,HttpStatus.CREATED);
                }

            //System.out.println("result" + result);


        }
        catch(ConnectException ex2) {
            System.out.println(ex2.getCause());
            return new ResponseEntity<String>("\"Coudl not connect\"",HttpStatus.CONFLICT);
        }

        catch (HttpClientErrorException ex) {
            System.out.println("value"+ ex.getStatusCode().value());
            statusCode=ex.getStatusCode().value();     
        }


        try { // If user does not exist by the given email we can POST
            if(statusCode==404) {
                if(user.getEmail()==null || user.getFirstName()==null || user.getLastName()==null) {
                     return new ResponseEntity<String>("\"Required fields are missing( required fields are email,firstName,LastName)\"",HttpStatus.BAD_REQUEST);
                }
                final String uriPost = "http://friend:5000/users";
                result= restTemplate.postForEntity(uriPost, user, String.class);
                System.out.println("result" + result);

                ResponsePojo pojo = mapper.readValue(result.getBody(), ResponsePojo.class);
                User userToRespond = new User(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
                toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
                return new ResponseEntity<User>(userToRespond,HttpStatus.CREATED);
            }
        }
            catch (HttpClientErrorException ex) {
                System.out.println("value"+ ex.getStatusCode().value());
                return ResponseEntity.status(ex.getRawStatusCode()).headers(ex.getResponseHeaders())
                        .body(ex.getResponseBodyAsString());
            }
    // istryniau daug tu throws not sure if thats that good

        System.out.println("Rip");
        return null;

    }
@PostMapping(“/todos/{toDoNoteId}/users”)
public ResponseEntity addUserToNote(@RequestBody User User,@PathVariable int toDoNoteId)抛出JsonParseException、JsonMappingException、ConnectException、IOException{
字符串email=user.getEmail();
最终字符串uri=”http://friend:5000/users/“+电子邮件;
RestTemplate RestTemplate=新RestTemplate();
ResponseEntity结果=空;
int statusCode=0;
ObjectMapper mapper=新的ObjectMapper();
//ResponseEntity结果=restemplate.getForEntity(uri,String.class);
//返回null;
请尝试{//如果用户存在,我们将只将其添加到ToDoNote中
result=restTemplate.getForEntity(uri,String.class);//此处引发异常
ResponsePojo pojo=mapper.readValue(result.getBody(),ResponsePojo.class);
User userToRespond=新用户(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
todonotetodonote=toDoNoteService.getToDoNoteById(toDoNoteId);
if(toDoNote.checkIfUserExists(userToRespond)=true){
返回新的ResponseEntity(“\”用户已在此注释中\“”,HttpStatus.CONFLICT);
}
否则{
toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
返回新的ResponseEntity(userToRespond,HttpStatus.CREATED);
}
//系统输出打印项次(“结果”+结果);
}
捕获(ConnectException ex2){
System.out.println(ex2.getCause());
返回新的响应属性(“Coudl not connect\”,HttpStatus.CONFLICT);
}
捕获(HttpClientErrorException-ex){
System.out.println(“value”+ex.getStatusCode().value());
statusCode=ex.getStatusCode().value();
}
如果我们可以发布的给定电子邮件中不存在用户,请尝试{//
如果(状态代码==404){
if(user.getEmail()==null | | user.getFirstName()==null | | | user.getLastName()==null){
return new ResponseEntity(“\”必填字段缺失(必填字段为email、firstName、LastName)\”,HttpStatus.BAD\u请求);
}
最后一个字符串uriPost=”http://friend:5000/users";
结果=restTemplate.postForEntity(uriPost、用户、String.class);
系统输出打印项次(“结果”+结果);
ResponsePojo pojo=mapper.readValue(result.getBody(),ResponsePojo.class);
User userToRespond=新用户(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
返回新的ResponseEntity(userToRespond,HttpStatus.CREATED);
}
}
捕获(HttpClientErrorException-ex){
System.out.println(“value”+ex.getStatusCode().value());
返回ResponseEntity.status(例如getRawStatusCode()).headers(例如getResponseHeaders())
.body(例如getResponseBodyAsString());
}
//istryniau daug tu不确定这是否好
系统输出打印项次(“Rip”);
返回null;
}
唯一有效的方法是捕获异常或RestClientException,不过我希望捕获ConnectException本身。有人知道我遗漏了什么吗?

这是关键部分:

嵌套异常是java.net.ConnectException

RestTemplate的
getForEntity
抛出一个RestClientException,它封装了ConnectException。这与引用父类型不同——RestClientException不会扩展ConnectException,因此您不能只是尝试捕获包装的类型

我不知道您为什么反对捕获异常或RestClientException。如果我只想拥有处理ConnectException的特定逻辑,我将捕获RestClientException,然后检查内部异常的类型(如果不是ConnectException,则重新调用)

比如说:

试试看{
response=restTemplate.getForEntity(…);
//为简洁起见省略
}捕获(RestClientException e){
if(例如,getCause()instanceof ConnectException){
//句柄连接异常
返回ResponseEntity.status(HttpStatus.CONFLICT).body(“无法连接”);
}
抛出e;//如果不是ConnectException,则重试
}

我明白了。感谢您的解释和关于如何处理异常的建议。:)另外,如果说我需要捕获更多嵌套异常,是否有一种比多个if子句更优雅的方法?您可以在rest模板上设置自己的错误处理程序,默认情况下,它会将400/500响应作为异常抛出,可以在此处查看快速摘要@Darrenforsyth它不会处理ResourceAccessExceptions
@PostMapping("/todos/{toDoNoteId}/users")
    public ResponseEntity<?> addUserToNote(@RequestBody User user,@PathVariable int toDoNoteId) throws JsonParseException, JsonMappingException, ConnectException, IOException{
        String email = user.getEmail();
        final String uri = "http://friend:5000/users/"+email;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result =null;
        int statusCode=0;
        ObjectMapper mapper = new ObjectMapper();
        //ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);

        //return null;

        try { // If user exists we will just add it to our ToDoNote

             result = restTemplate.getForEntity(uri, String.class); // exception thrown here

             ResponsePojo pojo = mapper.readValue(result.getBody(), ResponsePojo.class);
             User userToRespond = new User(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
             ToDoNote toDoNote = toDoNoteService.getToDoNoteById(toDoNoteId);
             if(toDoNote.checkIfUserExists(userToRespond)==true) {
                    return new ResponseEntity<String>("\"User already in this note\"",HttpStatus.CONFLICT);
             }
                else {
                    toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
                    return new ResponseEntity<User>(userToRespond,HttpStatus.CREATED);
                }

            //System.out.println("result" + result);


        }
        catch(ConnectException ex2) {
            System.out.println(ex2.getCause());
            return new ResponseEntity<String>("\"Coudl not connect\"",HttpStatus.CONFLICT);
        }

        catch (HttpClientErrorException ex) {
            System.out.println("value"+ ex.getStatusCode().value());
            statusCode=ex.getStatusCode().value();     
        }


        try { // If user does not exist by the given email we can POST
            if(statusCode==404) {
                if(user.getEmail()==null || user.getFirstName()==null || user.getLastName()==null) {
                     return new ResponseEntity<String>("\"Required fields are missing( required fields are email,firstName,LastName)\"",HttpStatus.BAD_REQUEST);
                }
                final String uriPost = "http://friend:5000/users";
                result= restTemplate.postForEntity(uriPost, user, String.class);
                System.out.println("result" + result);

                ResponsePojo pojo = mapper.readValue(result.getBody(), ResponsePojo.class);
                User userToRespond = new User(pojo.getData().getEmail(),pojo.getData().getFirstName(),pojo.getData().getLastName());
                toDoNoteService.getToDoNoteById(toDoNoteId).addUser(userToRespond);
                return new ResponseEntity<User>(userToRespond,HttpStatus.CREATED);
            }
        }
            catch (HttpClientErrorException ex) {
                System.out.println("value"+ ex.getStatusCode().value());
                return ResponseEntity.status(ex.getRawStatusCode()).headers(ex.getResponseHeaders())
                        .body(ex.getResponseBodyAsString());
            }
    // istryniau daug tu throws not sure if thats that good

        System.out.println("Rip");
        return null;

    }