java - java - SonarLint:返回空的Collection而不是null

我执行一个ajax调用,返回一个对象列表,如果在获取数据时发生了某些情况,try-catch response.setStatus(400),然后在前端显示错误,

getWriter() has already been called for this response

如果我把它留空,那么一切正常。


@GetMapping("/runquery")


@ResponseBody


public List<Map<String, Object>> runQuery(@RequestParam(name ="queryId") String queryId, @RequestParam(name ="formData") String formData, HttpServletResponse response) throws IOException {


 (...)



 try {


 queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);



 for (Map<String, Object> map : queryResult) {


 Map<String, Object> newMap = new HashMap<>();


 for (Map.Entry<String, Object> entry : map.entrySet()) { 


 String key = entry.getKey();


 Object value = entry.getValue();



 if (key.contains(".")) {


 key = key.replace(".","_");


 newMap.put(key, value);


 } else {


 newMap.put(key, value);


 }


 }


 queryResultFinal.add(newMap);


 }



 } catch (Exception e) {


 response.setStatus(400);


 response.getWriter().write(e.getMessage());


 return null; <-- SonarLint notification


 }



 return queryResultFinal; 


}



时间: 原作者:

我建议不要捕获异常,而是抛出异常,并在控制器中使用异常处理程序方法来处理它,

例如,如下所示:


@ExceptionHandler


@ResponseStatus(HttpStatus.BAD_REQUEST)


public void handleException(Exception e) {


 log.error("Exception during request", e);


}



或者直接处理:


@ExceptionHandler


public ResponseEntity<?> handleException(Exception e) {


 return ResponseEntity.badRequest().body(e.getMessage()).build();


}



切换到异常处理程序后,可以从普通方法中移除HttpServletResponse response参数。

原作者:
...