HttpUrlConnection 未显示调用的 java 程序抛出的异常

HttpUrlConnection not showing exception thrown by called java program

我有服务抛出 RuntimeException,它与 ajax 调用一起工作正常。如果我使用来自另一个 java 程序异常字符串的 HttpUrlConnection 调用该服务,而不是显示 'Internal Server Error' 和响应代码 500.

@Path("poService")
public class PoService {
    @Context
    private UriInfo context;
    @GET
    @Path("getPo/{poNo}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getPo(@PathParam("poNo") int poNo ) throws Exception{
       String urlStr = AppConstant.WEBOLIS_PATH + "po.htm?getPoForSrnConsReport=true&pono="+poNo ;
       URL url = new URL(urlStr);
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       //con.setRequestProperty("User-Agent", AppConstant.USER_AGENT);
       int responseCode = con.getResponseCode();
       System.out.println("\nSending 'GET' request to URL : " + url);
       System.out.println("Response Code : " + responseCode);
       System.out.println("Response Code : " + con.getResponseMessage());

       BufferedReader in = new BufferedReader(new  InputStreamReader(con.getInputStream()));
       String inputLine;
       StringBuffer response = new StringBuffer();
       while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
       }
       in.close();

       if( responseCode!=200 ){ // if any Error
         //throw new WebolisApiException( responseCode,  response.toString());
       }else{
       }
       return Response.ok( response.toString(),   MediaType.APPLICATION_JSON).build();
    }


}

这是我调用另一个 java Spring 控制器的 REST 方法之上。

 @RequestMapping( value="/po", method=RequestMethod.GET,params=  {"getPoForSrnConsReport"})  //,consumes="application/json" 
        @ResponseBody ModelMap getPoForSrnConsReport(HttpServletResponse response,
                                        @RequestParam(value = "pono" )   Integer poNo) throws Exception {
            ModelMap m = new ModelMap();
            PoService poService = new PoService();
            Po po = poService.getPo(poNo, poService.ALL_ITEMS , Boolean.FALSE);
            m.addAttribute("po",po);
            return m;
       }

我在 PoService 中抛出自定义异常'PO not Found'此字符串在 REST 方法中不可用

尝试打开与发送错误代码的服务器的连接将引发异常,您需要捕获该异常。当您收到错误响应代码时,您也不能使用 getInputStream()。您需要使用 getErrorStream():

BufferedReader in = null;
try {
    in = new BufferedReader(new InputStreamReader(con.getInputStream()));
}
catch(IOException e) {
    // handle specific exceptions here
}

int responseCode = -1;
try {
    responseCode = con.getResponseCode();
}
catch(IOException e) {
    // handle specific exceptions here
}

// override the input if you got an error and an error stream is available
if (in==null && responseCode!=200 && con.getErrorStream() != null) {
    in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}