[英]How to catch the exception thrown from a lambda
我可能在這里缺少明顯的東西,但是如何捕獲從lambda拋出的IOException
?
Future<Response<R>> futureResp = pool.submit(() -> {
Response<R> res;
try {
res = call.execute();
} catch (IOException e) {
throw new IOException(e);
}
return res;
});
整個方法如下所示:
@Override
public RetrofitResponse<R> adapt(Call<R> call) {
if (networkUtil.isOnline( ctx )) {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Response<R>> futureResp = pool.submit(() -> {
Response<R> res;
try {
res = call.execute();
} catch (IOException e) {
throw new IOException(e);
}
return res;
});
Response<R> resp;
try {
resp = futureResp.get();
} catch (Exception e) {
e.printStackTrace();
return new RetrofitResponse<>( ErrorStatus.PROCESSING_ERROR, e.getMessage() );
}
if (resp != null) {
return new RetrofitResponse<>( new ApiResponse<>(resp) );
} else {
return new RetrofitResponse<>( ErrorStatus.PROCESSING_ERROR, "Response is null" );
}
} else {
return new RetrofitResponse<>( ErrorStatus.NETWORK_ERROR, "No internet network detected!" );
}
}
我基本上想將錯誤包裝在一個自定義對象中,該對象保留有關可能的錯誤的狀態,這些錯誤不一定與缺少網絡連接或http錯誤有關。
在另一個try-catch塊中扭曲該塊不起作用,因為ide指示沒有要捕獲的IOException。
這與lambda表達式完全無關。 因此,您無需“從lambda”捕獲並重新拋出異常; 您可以簡單地像
Future<Response<R>> futureResp = pool.submit(() -> call.execute());
關鍵點在於,這將調用submit(Callable)
,並且Callable
接口允許引發已檢查的異常。 而且Future.get()
指出:
拋出:
…
ExecutionException-如果計算引發異常
因此,當您在get()
調用中catch(ExecutionException)
時,其原因將是拋出的IOException
(如果有)。
您需要捕獲原始的Exception
並將其作為UncheckedException
拋出,可能是您自己的擴展了前面提到的異常,並將原始異常作為其原因。
然后捕獲此UncheckedException
並在需要時從中找出原因。
您需要將錯誤重新拋出為UncheckedException
catch(IOException e) {
throw new RuntimeException(e);
}
或擴展RuntimeException並拋出一個自定義變量。
您將來會收到錯誤。get()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.