Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.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 web服务能否从其他服务器上的web服务获取自定义错误消息?_Java_Spring Boot - Fatal编程技术网

Java web服务能否从其他服务器上的web服务获取自定义错误消息?

Java web服务能否从其他服务器上的web服务获取自定义错误消息?,java,spring-boot,Java,Spring Boot,我在服务器a上运行了一个web服务,它在Java ResponseEntity对象中返回一条自定义错误消息,如下所示: return new ResponseEntity<String>("My custom error message.", HttpStatus.BAD_REQUEST); 当服务器B从服务器A接收到错误400时,conn.getInputStream()抛出一个IOException,该IOException被捕获,但“我的自定义错误消息”在异常中丢失 catc

我在服务器a上运行了一个web服务,它在Java ResponseEntity对象中返回一条自定义错误消息,如下所示:

return new ResponseEntity<String>("My custom error message.", HttpStatus.BAD_REQUEST);
当服务器B从服务器A接收到错误400时,conn.getInputStream()抛出一个IOException,该IOException被捕获,但“我的自定义错误消息”在异常中丢失

catch (IOException e) {
    return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
catch(IOE异常){
返回新的ResponseEntity(例如getMessage(),HttpStatus.BAD_请求);
}
服务器B是否可以从服务器A返回自定义错误消息?怎样才能做到呢

我正在使用Java8、SpringBoot2.0.2、Tomcat9和SwiggerUI2.8来测试web服务


更新:如果服务器A返回代码200而不是400,则不会在服务器B上引发IOException。相反,会引发JsonParseException,服务器B会返回“我的自定义错误消息”

我认为发生这种情况的原因是,尽管从中正确抛出的异常在
conn.getInputStream
中处理,它会看到错误的请求异常。 我可以猜到一个可能的解决方案是,在让输入流读取器的对象检查连接是否抛出异常之前,以某种方式进行检查

try{
    conn.open();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()));
    }catch(Exception e){
     return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
试试看{
conn.open();
BufferedReader br=新的BufferedReader(新的InputStreamReader((conn.getInputStream()));
}捕获(例外e){
返回新的ResponseEntity(例如getMessage(),HttpStatus.BAD_请求);
}

类似于conn.open的方法应在生成输入流读取器对象之前引发自定义异常

如果服务器B需要JSON,请尝试在字符串值中添加引号。这将删除“无法解析JSON.Raw result:”但客户端仍然不知道服务器返回HTTP错误400的原因。我可以让服务器B在向服务器A发送请求之前检查正文的内容,但服务器A已经检查了它接收到的内容。我希望避免在两台服务器上重复代码,但这似乎是不可避免的。
try{
    conn.open();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()));
    }catch(Exception e){
     return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}