我的团队为我的项目实现了Sonar代码覆盖,并且一个类中的方法抱怨错误'要么删除这个无用的对象实例化类“ResponseEntity”或使用它'。如果我删除该行它抱怨它会工作。但我也想处理这个错误。
任何有关如何处理此事的建议都将受到赞赏
@RequestMapping(value = "/**/identity", method = RequestMethod.POST)
public ResponseEntity<String> createIdentity(@RequestBody @NotNull Heartbeat heartbeat) {
//Validate
if (StringUtils.isEmpty(heartbeat.getHostname())
|| StringUtils.isEmpty(heartbeat.getEnvironment())
|| StringUtils.isEmpty(heartbeat.getProcessSignature())) {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
try {
byte[] encodedValue = identityService.createIdentity(heartbeat.getHostname(), heartbeat.getEnvironment(),
heartbeat.getProcessSignature());
return ResponseEntity.ok(new String(encodedValue));
} catch (BadPaddingException | IllegalBlockSizeException e) {
log.error("Unable to create entity for the request", e);
new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); // Sonar Complaint
}
return ResponseEntity.ok().build();
}
答案 0 :(得分:2)
问题是您没有返回您认为自己处于错误情形中的响应。您可以通过正确返回INTERNAL_SERVER_ERROR响应来解决此问题。
索纳只是指出了可能存在的缺陷。@RequestMapping(value = "/**/identity", method = RequestMethod.POST)
public ResponseEntity<String> createIdentity(@RequestBody @NotNull Heartbeat heartbeat) {
//Validate
if (StringUtils.isEmpty(heartbeat.getHostname())
|| StringUtils.isEmpty(heartbeat.getEnvironment())
|| StringUtils.isEmpty(heartbeat.getProcessSignature())) {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
try {
byte[] encodedValue = identityService.createIdentity(heartbeat.getHostname(), heartbeat.getEnvironment(),
heartbeat.getProcessSignature());
return ResponseEntity.ok(new String(encodedValue));
} catch (BadPaddingException | IllegalBlockSizeException e) {
log.error("Unable to create entity for the request", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return ResponseEntity.ok().build();
}