所以这是我当前的rest-api端点的实现,我想处理某种极端情况,例如找不到用户或公寓,所以我会抛出合适的异常,但是如何显示我在 Controller 中处理它?目前它还没有真正工作,如果我设置了一个不存在的 id,它会照常工作,并且我没有收到相应的错误消息。
服务层:
public void delete(Long flatId) {
flatRepository.findById(flatId).ifPresentOrElse(flat -> {
List<User> residents = flat.getResidents();
residents.forEach(resident -> resident.setFlat(null));
flatRepository.delete(flat);
},
() -> new ResourceNotFoundException("Flat " + flatId + " found"));
}
Controller 层:
@DeleteMapping("/flats/{flatId}")
public void deleteFlat(@PathVariable Long flatId) {
flatService.delete(flatId);
}
全局异常处理程序:
@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public final ErrorDetails handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ErrorDetails(LocalDateTime.now(), ex.getMessage(), 404);
}
@ExceptionHandler(ResourceAlreadyDefinedException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public final ErrorDetails handleResourceAlreadyDefinedException(ResourceAlreadyDefinedException ex) {
return new ErrorDetails(LocalDateTime.now(), ex.getMessage(), 409);
}
}
更新:我创建了这个全局异常处理程序,但是如果我向我的 api 发送一个带有不存在 id 的删除请求,它不会向我发送 404,它只会回复 200。而如果我有一个像这样的返回值在这种情况下,它按预期工作。
public Flat get(Long id) {
return flatRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Flat " + id + " not found"));
}
@GetMapping("/flats/{flatId}")
public ResponseEntity<Flat> getFlat(@PathVariable Long flatId) {
return ResponseEntity.ok(flatService.get(flatId));
}
最佳答案
您可以将@ControllerAdvice
与@ExceptionHandler
结合使用,为所有 Controller 和特定类型的异常实现全局异常处理。
看here例如。
关于spring - 服务和 Controller 层异常处理设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677994/