【发布时间】:2014-11-19 17:01:35
【问题描述】:
我有以下代码重复代码,所以我做错了,必须有更好的方法来做到这一点。我在 catch 部分有一组通用的语句。我不能把它放在 finally 块中,因为这些仅用于异常情况。除了制作单独的方法来保存此代码之外,我还能采取其他方法吗?
public MyResponseDto doSomeWork(MyRequestDto) {
....
String jsonStr = null;
try {
jsonStr = new ObjectMapper().writeValueAsString(MyRequestDto);
} catch (JsonGenerationException e) {
log.error(e.getMessage());
myResponseDto .setWorkDone(false);
myResponseDto .setErrorMessage(e.getMessage());
return myResponseDto ;
} catch (JsonMappingException e) {
log.error(e.getMessage());
myResponseDto .setWorkDone(false);
myResponseDto .setErrorMessage(e.getMessage());
return myResponseDto ;
} catch (IOException e) {
log.error(e.getMessage());
myResponseDto .setWorkDone(false);
myResponseDto .setErrorMessage(e.getMessage());
return myResponseDto ;
}
myResponseDto = postWorkRequest(jsonStr);
return myResponseDto ;
}
【问题讨论】:
-
多异常捕获?无论如何,制作方法有什么问题?
标签: java refactoring