java异常的注意事项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37012236/article/details/79098400

我们在捕获到异常后,在cath中打印了异常信息,并且向上抛出了异常,这时候异常信息不能打印堆栈信息,只有一个错误提示,如果不调用initCause是无法打印出所有异常链的如下所示:

} catch (Exception e) {
    LOGGER.error("查询服务单管理列表异常", e);
    throw  new RefundException(
ExceptionDict.QUERY_USER_PRIVIDER_LIST_FAILURE_ERROR_CODE,

ExceptionDict.QUERY_USER_PRIVIDER_LIST_FAILURE_ERROR_MSG);

}  

以上代码无法打印堆栈信息,应该改为:

} catch (Exception e) {
    LOGGER.error("查询服务单管理列表异常", e);
    RefundException refundException = new RefundException(
            ExceptionDict.QUERY_USER_PRIVIDER_LIST_FAILURE_ERROR_CODE,
            ExceptionDict.QUERY_USER_PRIVIDER_LIST_FAILURE_ERROR_MSG);
    refundException.initCause(e);
    throw refundException;
}


或者在自定义异常中增加构造方法:
public ItemException(String code, String message, Exception e) {
        super(code,message,e);
}

在抛异常时在参数中传入e

} catch (Exception e) {
            log.error("批量插入商品扩展信息失败 - list:{},e:{}",list.toString(),e);
throw new ItemException(ExceptionDict.INSERT_SHOP_ITEM_EXPANDS_ERROR_CODE,ExceptionDict.INSERT_SHOP_ITEM_EXPANDS_ERROR_MSG, e);
 }



猜你喜欢

转载自blog.csdn.net/qq_37012236/article/details/79098400