当试图在方法中引发新异常而不是直接引发异常时,我的IDE会在catch块中显示错误“缺少返回语句”。
REST控制器的缩小样本:
@RestController
public class RootController {
protected final Logger log = Logger.getLogger("myLogger");
@PostMapping(
value={"sample/",
"sample/123"},
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Object getFileContentPost (@RequestBody Request payload) {
return checkPayloadAndRespond(payload.getFileName());
}
private Object checkPayloadAndRespond(String fileName) throws ResponseStatusException {
if (StringUtils.isEmpty(fileName))
logErrorAndThrowResponseException(HttpStatus.BAD_REQUEST, "Field fileName is empty or missing!", null);
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("/static/json/" + fileName , Object.class);
} catch (IOException e) {
//line causing ERROR "missing return statement":
logErrorAndThrowResponseException(HttpStatus.INTERNAL_SERVER_ERROR, "Could not parse file!, e);
}
}
private void logErrorAndThrowResponseException(HttpStatus status, String reason, @Nullable Throwable cause) throws ResponseStatusException {
log.error("Error occurred: " + reason + ", returning status: " + status);
throw new ResponseStatusException(status, reason, cause);
}
}
工作示例:如果我直接使用throw new
语句而不使用方法:
@RestController
public class RootController {
protected final Logger log = Logger.getLogger("myLogger");
@PostMapping(
value={"sample/",
"sample/123"},
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Object getFileContentPost (@RequestBody Request payload) {
return checkPayloadAndRespond(payload.getFileName());
}
private Object checkPayloadAndRespond(String fileName) throws ResponseStatusException {
if (StringUtils.isEmpty(fileName))
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Field fileName is empty or missing!", e);
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("/static/json/" + fileName , Object.class);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Could not parse response file!", e);
}
}
}
解决此问题的最佳方法是什么?
我要做的就是在抛出ResponseStatusException时实际创建一个日志。
提前感谢。
所以我猜是void返回类型导致了这个问题。
我现在通过返回一个实际的响应来解决它,然后抛出:
private Object checkPayloadAndRespond(String fileName) throws ResponseStatusException {
if (StringUtils.isEmpty(fileName))
throw logErrorAndThrowResponseException(HttpStatus.BAD_REQUEST, "Field fileName is empty or missing!", null);
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("/static/json/" + fileName , Object.class);
} catch (IOException e) {
throw logErrorAndThrowResponseException(HttpStatus.INTERNAL_SERVER_ERROR, "Could not parse file!, e);
}
}
private ResponseStatusException logErrorAndThrowResponseException(HttpStatus status, String reason, @Nullable Throwable cause) {
log.error("Error occurred: " + reason + ", returning status: " + status);
return new ResponseStatusException(status, reason, cause);
}
}