[英]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.