我正在尝试将值分配给with put Controller尚未存在的值。通常它应该返回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);
}
}
有几个选项。
在 findById
方法上有 CricketerService
投掷 Exception
(可能是域特异性 CricketerNotFoundException
或类似的东西(,并为此添加 @ExceptionHandler
。
@ExceptionHandler(CricketerNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
private void handleCricketerNotFoundException(final CricketerNotFoundException cnfEx) {
// Log, do anything else...
}
(您也可以在CricketerNotFoundException
类本身上添加@ResponseStatus
。(
有CricketerService.findById
返回null
如果找不到它,并且 hander> hander 该情况:
public ResponseEntity<Cricketer> updateCricketer(
@PathVariable("id") Long id,
@RequestBody @Valid Cricketer cricketer) {
@Nullable Cricketer cCricketer=cricketerService.findById(id);
if (cricketer == null) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
cCricketer.setId(id);
cCricketer.setCountry(cricketer.getCountry());
cCricketer.setName(cricketer.getName());
cCricketer.setHighestScore(cricketer.getHighestScore());
cricketerRepository.save(cCricketer);
return new ResponseEntity<Cricketer>(cCricketer, HttpStatus.OK);
}