首页 > 解决方案 > Java-自定义异常中的try-catch异常问题

问题描述

我有一个自定义 Java 异常类CustomRestException

 import org.codehaus.jettison.json.JSONObject;

 public class CustomRestException extends Exception{

    private String httpStatusMessage;    
    private Integer httpStatusCode;

    private String endpointBody;
    private String callType;        
    private List<HashMap<String,String>> headerParams;
    private List<HashMap<String,String>> queryParams;

    private JSONObject endPointErrorResponse;   

    public CustomRestException (RestCallParameters p,String type,String url,String body,UniformInterfaceException ue) {

       super(p.getCollectionErrMsg());      
       this.endpointBody= body;
       this.endPointUrl = url;
       this.callType = type;
       setUniformInterfaceExceptionParameters(ue);
    }

    private void setUniformInterfaceExceptionParameters(UniformInterfaceException ue) {
        try {
            this.httpStatusMessage = ue.getMessage();    
            this.httpStatusMessage  = ue.getResponse().getClientResponseStatus().toString();
            this.httpStatusCode = ue.getResponse().getStatus();

            this.endPointErrorResponse =
                    new JSONObject(ue.getResponse().getEntity(String.class));            
        }
        catch (Exception ex) {
             LOGGER.info("[setUniformInterfaceExceptionParameters]  Ecnountered error ",ex);
        }
    }
}

我从一个方法中抛出这个 CustomRestException:

public String myMethod() throws CustomRestException {
   try{
       //make some rest call here
   }catch(UniformInterfaceException ue){
       throw new CustomRestException (p,"POST",url,p.getReqBody(),ue);   
   }
}

然后,我在CustomRestException其他地方发现了这个:

public Response myEndPointMethod(){
    try{
        //some code
        myClassObj.myMethod();     //calling myMethod() above
        //some code

    } catch (CustomRestException e) {             
       LOGGER.error("(someMessage) CustomRestException ", e);       
    }




我的问题

this.endPointErrorResponse = new JSONObject(ue.getResponse().getEntity(String.class));

如果此行抛出任何异常(我JSONException到目前为止只看到过),则程序在 catch 块中执行此记录器后终止:

LOGGER.info("[setUniformInterfaceExceptionParameters]  Ecnountered error ",ex);



我的期望 应该调用

记录器LOGGER.error("(someMessage) CustomRestException ", e);myEndPointMethod()



我们不应该在自定义异常中处理(try-catch)异常吗?
知道我哪里出错了吗?

标签: javaexception-handlingcustom-exceptions

解决方案


推荐阅读