我有一个关于异常处理的简单问题。 我目前有一个分为多个层的应用程序: Controller 、服务、存储库,我的问题如下:异常处理应该由 Controller 还是服务来完成?
例子:
Controller :
@PostMapping(value = "/{id}/parents", produces = "application/json; charset=utf-8")
public ResponseEntity<AccommodationRequestDTO> resident(@PathVariable Long id, @Valid @RequestBody ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
AccommodationRequestDTO saved;
try {
saved = this.service.parents(id, parentsAndUrgencyContactDTO);
} catch (Exception e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR,
"Failed to save request", e);
}
return ResponseEntity.ok(saved);
}
服务:
public AccommodationRequestDTO parents(Long id, ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
Optional<AccommodationRequest> accommodationRequest = repository.findById(id);
if (accommodationRequest.isPresent()) {
AccommodationRequest saved = accommodationRequest.get();
Parent firstParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getFirstParent());
Parent secondParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getSecondParent());
firstParent = parentRepository.save(firstParent);
secondParent = parentRepository.save(secondParent);
saved.setFirstParent(firstParent);
saved.setSecondParent(secondParent);
saved = this.repository.save(saved);
return mapper.toDTO(saved);
} else {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, " with id " + id + " not found !");
}
}
什么是最佳实践,我应该从 Controller 中删除我的 try-catch 并将其放入我的服务中吗?因为使用此代码,我的 404 异常被 Controller 捕获覆盖。
最佳答案
如果你想抛出异常,在服务层抛出。
最好再定义一个名为exception的包。
并在其中包含您的自定义异常、异常响应和异常处理程序。
我的代码结构如下:
package com.***.demo.exception;
public class DataNotFound extends EntityNotFoundException {
public DataNotFound(String message) {
super(message);
}
}
package com.***.demo.exception;
@Data
@AllArgsConstructor
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
}
package com.***.demo.exception;
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(DataNotFound.class)
public ResponseEntity<?> dataNotFoundExceptionHandling(Exception exception, WebRequest request) {
return new ResponseEntity<>(new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false)), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> globalExceptionHandling(Exception exception, WebRequest request) {
return new ResponseEntity<>(new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false)), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
希望你得到了答案。
关于Spring Boot异常处理最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66762006/