【发布时间】:2021-01-24 10:56:23
【问题描述】:
我正在处理我的应用程序中的异常。在我的服务中,我有这个方法:
public Optional<Entity> getEntityById(Long id) {
return Optional.of(EntityMapper.fromEntityToDto(repository
.findById(id)
.orElseThrow(() -> new EntityNotFoundException("No entry was found for" + " id: " + id))));
}
在我的异常处理程序中,我有以下内容
@ControllerAdvice
public class ControllerAdvisor extends ResponseEntityExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<Object> handleEntityNotFoundException(EntityNotFoundException ex, WebRequest request) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, "Entity not found", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
}
我已经看到他们这样做here 和here 的例子,但在我看来这像是对HttpStatus 的滥用。该资源是 API 端点(这很好),而不是未找到的实体。处理此用例的最佳方法是什么?
根据 IQbrod 的回答,我创建了一个例外:
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public class MyEntityNotFoundException extends RuntimeException {
public MyEntityNotFoundException(String message) {
super(message);
}
}
我现在抛出的不是EntityNotFoundException
【问题讨论】:
标签: java exception http-status-code-404 http-status-codes