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

时间:2019-07-04 08:28:30

标签: java spring-boot validation http-status-codes

我正在尝试为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);
    }
}

1 个答案:

答案 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