2012-11-29 6 views
2

최근 스레드를 구현하기 위해 내부 클래스를 많이 사용하는 레거시 코드를 상속 받았습니다. 이 내부 클래스는 현재 JFrame 코드를 모 놀리 식으로 만들고 따라서 코드를 다시 작성하여 SwingWorker 클래스를 사용하려고합니다.Future에서 던져진 특정 예외를 잡는 방법?

SwingWorker 클래스는 웹 서비스에 대한 여러 API 호출을 한 다음 결과를 반환합니다. 이것은 비동기식이기 때문에 분명히 스레드 내에서 가장 잘 수행됩니다. 현재 웹 서비스가 작동하는 방식은 요청을 확인하기 위해 몇 가지 인증 호출이 필요합니다. 이러한 호출은 분명히 오류를 반환 할 수 있습니다. 이 웹 서비스 호출이 인증되지 않으면 SwingWorker 내에서 사용자 지정 예외가 throw됩니다.

SwingWorker의 (백그라운드 스레드)

@Override 
protected String doInBackground() throws Exception { 
    if (!authenticationClient.authenticate(userid)) { 
     throw new PlaceOrderException("Failed to authenticate client"); 
    } 

    return orderClient.placeOrder(...); 
} 

메인 GUI (EDT 스레드)

// On the EDT 
PlaceOrderWorker placeOrderWorker = new PlaceOrderWorker(...) { 
    // This method is invoked when the worker is finished its task 
    @Override 
    protected void done(){ 
     try { 
      String orderID = get(); 

      // Update some GUI elements using the orderID 

     } catch(PlaceOrderException e) { 
      JOptionPane.showMessageDialog(this, "Please review your order", e.getMessage(), JOptionPane.ERROR_MESSAGE, null); 
     } catch (Exception e) { 
      LOGGER.error("Error placing order", e); 
     } 
    } 
} 

오류 : 나는 다음과 유사 코드를 표준 Future 패턴을 사용하여 회선에서 발생합니다 :

catch(PlaceOrderException e) { 
    JOptionPane.showMessageDialog(this, "Please review your order", e.getMessage(), JOptionPane.ERROR_MESSAGE, null); 
} 

Java는이 예외가 발생하지 않는다고 주장합니다. 그리고이 PlaceOrderException을 던질 수 -

exception PlaceOrderException is never thrown in body of corresponding try statement 

는 지금은 get를 호출하면 예외가 스레드에서 슬로우 다시되도록 할 것이라는 점을 알고있다. 이 특정 예외를 어떻게 잡을 수 있습니까? 내 코드를 구조화 한 이유는 배경 스레드에서 throw 될 수있는 예외가 많아서 사용자에게 JDialog을 통해 메시지를 표시하게하려는 것입니다. 주 GUI 클래스 내에서 done 메서드를 선언하는 이유는 EDT 스레드 내에서 JDialog을 인스턴스화해야하기 때문입니다. 이것은 나에게 훌륭한 디커플링을 허용한다.

누구든지 instanceof을 사용하여이 예외를 캡처 할 수있는 방법을 알고 있습니까? 아니면 사용할 더 좋은 패턴을 제안 할 수 있습니까? 아마도 SwingWorker가 잘못된 선택일까요?

+0

비트 더러운 :; 경우 (false)를'추가) (새 PlaceOrderException을 던져 try 블록이이 [Q & A] (HTTP를 참조 – zapl

+0

에': // 11053865/230513). – trashgod

답변

5

캐치 ExecutionException 다음 그 원인을 조사 :

try { 
     String orderID = get(); 

     // Update some GUI elements using the orderID 

    } catch(ExecutionException e) { 
     Throwable cause = e.getCause(); 
     if (cause instanceof PlaceOrderException) 
     { 
      JOptionPane.showMessageDialog(
       this, 
       "Please review your order", 
       cause.getMessage(), 
       JOptionPane.ERROR_MESSAGE, 
       null 
      ); 
     } 
     else 
     { 
      LOGGER.error("Error placing order", e); 
     } 
    } catch (Exception e) { 
     LOGGER.error("Error placing order", e); 
    } 
관련 문제