如何通过异常处理更改HTTP状态代码



我正在尝试将值分配给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);
}

相关内容

最新更新