#URL호출 서버에서 response 오류 발생하였을 때, con.getInputStream()에서 IOException이 발생 : 뿌려주는 오류 메세지를 잡지 못함

HttpsURLConnection con = (HttpsURLConnection)connectUrl.openConnection();

.....

InputStreamReader ir     = new InputStreamReader(con.getInputStream(), charSet);




# 이를 해결하고자 오류가 발생했을 경우(con.getResponseCode()가 400 이상일 경우) con.getErrorStream()으로 받는다.

HttpsURLConnection con = (HttpsURLConnection)connectUrl.openConnection();

....

// SERVER ERROR CHECK

if(con.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST){
/* not error from server : con.getInputStream() */
ir = new InputStreamReader(con.getInputStream(), charSet);
postRes = new BufferedReader(ir);
while ((resultJson = postRes.readLine()) != null){
resultBuffer.append(resultJson);
}
con.disconnect();
}else{
/* error from server : con.getErrorStream() */
ir = new InputStreamReader(con.getErrorStream(), charSet);
postRes = new BufferedReader(ir);
while ((resultJson = postRes.readLine()) != null){
resultBuffer.append(resultJson);
}
con.disconnect();
/* Exception 던지지 않으면 오류가 났음에도 불구하고 로직이 계속 진행되므로 Exception 던져서 오류가 났다는 것을 전달한다. */
throw new Exception(resultBuffer.toString());
}



어떤 오류가 발생 했는지 로그로 출력된다.

이 때 주의할 점은 오류가 발생했을 때 Exception을 반드시 던져주어야 한다. 만약 Exception을 던지지 않는다면 오류가 났음에도 불구하고 로직이 계속 진행되므로 오류가 났다는 것을 전달해주어야 한다.


'Java' 카테고리의 다른 글

encoding 별로 JAVA 문자열 byte단위로 자르기  (0) 2018.08.13
클래스로더 오류 관련  (0) 2018.02.19

+ Recent posts