[英]Check if resource exists before inserting to the database or wait until the DAO throw the Exception?
我有兩條路:
/students
/students/{id}/addresses
...具有以下行為:
POST
到/students
- 201 Created
(如果成功創建了Student) POST
到/students/{id}/addresses
- 201 Created
(如果在請求的用戶下成功創建了地址) 現在,設想的情況下,客戶端POST
到/students/12/addresses
,但有一個與ID = 12沒有學生。
我應該如何處理這種情況?
我應該插入而不進行任何檢查並等待Hibernate拋出異常,還是應該在插入之前檢查Student的存在性?
第一種選擇:
StudentController.java
@Autowired
private AddressService addressService;
@PostMapping("/students/{id}/addresses")
public ResponseEntity<?> handleRequestOfCreateAddressToStudent(@PathVariable("id") Long studentId, @RequestBody Address address) {
address.setStudent(new Student(studentId));
Address createdAddress = addressService.saveAddress(address);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").build(createdAddress.getId());
return ResponseEntity.created(location).build();
}
AddressService.java
@Autowired
private AddressRepository addressRepository;
public Address saveAddress(Address address) {
// omitted for brevity...
return addressRepository.save(address);
}
這樣,由於我使用的是Spring,因此應用程序將拋出DataIntegrityViolationException
,因為違反了約束(不存在具有此類ID的Student與該Address綁定)。 而且,由於我需要將響應發送給客戶端,因此我必須轉換拋出的異常。
第二個選擇:
StudentController.java
@Autowired
private StudentService studentService;
@Autowired
private AddressService addressService;
@PostMapping("/students/{id}/addresses")
public ResponseEntity<?> handleRequestOfCreateAddressToStudent(@PathVariable("id") Long studentId, @RequestBody Address address) throws StudentNotFoundException {
Student student = studentService.findById(studentId);
if(student == null)
throw new StudentNotFoundException("message");
address.setStudent(new Student(studentId));
Address createdAddress = addressService.saveAddress(address);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").build(createdAddress.getId());
return ResponseEntity.created(location).build();
}
這樣,我不需要翻譯異常,因為我已經知道Student不存在,因此我可以拋出自定義異常。
我對兩種方法的想法:
哪種方法是解決此問題的最佳方法?
我應該等待DAO拋出異常,還是應該通過檢查Student是否存在來防止拋出異常?
您對2個結論的看法是正確的,但我想補充一件事供您考慮。 僅當您要在遇到這種特定情況時執行某些特定操作時,第二個選項才是您的好選擇。 如果您只是要像記錄所有其他錯誤一樣記錄一條錯誤消息,那么將這種特殊情況與其他情況區分開是沒有意義的。
話雖如此:如果您的業務邏輯中沒有針對此類事件的特殊處理,請選擇選項1。否則,選擇選項2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.