我正在尝试为id不存在的put控制器分配值。通常情况下,它应该返回404,但返回500。如何转换为404?我尝试使用其他方法,但这不能正常工作。
@PutMapping("/api/cricketer/{id}")
public ResponseEntity<Cricketer> updateCricketer(@PathVariable("id") Long id, @RequestBody @Valid Cricketer cricketer) {
Cricketer cCricketer=cricketerService.findById(id);
cCricketer.setId(id);
cCricketer.setCountry(cricketer.getCountry());
cCricketer.setName(cricketer.getName());
cCricketer.setHighestScore(cricketer.getHighestScore());
cricketerRepository.save(cCricketer);
if (cCricketer.getId()!=null){
return new ResponseEntity<Cricketer>(cCricketer,HttpStatus.OK);
}
else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
答案 0 :(得分:2)
几个选择。
已在CricketerService
方法上抛出Exception
(可能是特定于域的CricketerNotFoundException
或类似的东西),并为此添加了findById
。 / p>
@ExceptionHandler
(您还可以在@ExceptionHandler(CricketerNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
private void handleCricketerNotFoundException(final CricketerNotFoundException cnfEx) {
// Log, do anything else...
}
类本身上添加@ResponseStatus
。)
如果找不到CricketerNotFoundException
,则返回CricketerService.findById
并处理这种情况:
null