【发布时间】:2020-10-08 17:06:39
【问题描述】:
我有以下 Spring Boot MySQL 查询:
visitorrepository.save(newvisitor)
在执行此 MySQL 查询时,我想以以下格式返回成功 JSON 或失败 JSON:
成功状态:
{
"success": true,
"message": "Some Helpful Message",
"data": { } //This would be the newvisitor JSON that includes the primary key (id)
}
故障状态:
{
"success": false,
"message": "Some Helpful Message",
"error_code": "404", // This should be whatever error number was returned
"data": { } //This would be the newvisitor JSON that does not include the primary key (id)
}
在角度上,响应被捕获如下
this.http.post('http://localhost:8080/v1/api/post', this.visitor.value).toPromise().then((response:any) => {
console.log(response);
})
post.java
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class post {
@Autowired
visitorrepository visitorrepository;
@PostMapping("/v1/api/post")
public void insert(@Valid @RequestBody newvisitor newvisitor) {
try {
visitorrepository.save(newvisitor);
return // Success State JSON
} catch () {
return // Error State JSON
}
}
}
newvisitor.java
@Getter
@Setter
@Entity
@Table(name = "visitors")
public class newvisitor {
@Id
@GeneratedValue
private Long id;
@Size(min=1, max=250)
@NotBlank
private String firstname;
@NotBlank
private String lastname;
@NotBlank
private String month;
@NotBlank
private String day;
@NotBlank
private String year;
@NotBlank
private String socialsecuritynumber;
@NotBlank
private String street1;
private String street2;
@NotBlank
private String city;
@NotBlank
private String state;
@NotBlank
private String zip;
@NotBlank
private String phone;
@Email
@NotBlank
private String email;
public newvisitor(){
super();
}
public newvisitor(String firstname, String lastname, String month, String day, String year, String socialsecuritynumber, String street1, String street2, String city, String state, String zip, String phone, String email) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.month = month;
this.day = day;
this.year = year;
this.socialsecuritynumber = socialsecuritynumber;
this.street1 = street1;
this.street2 = street2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
}
visitorrepository.java
@Repository
public interface visitorrepository extends CrudRepository<newvisitor, Long> {
}
我们的想法是捕获所有内容,从 MySQL 数据库未连接、无效数据输入、重复记录,基本上是任何阻止初始查询 visitorrepository.save(newvisitor) 工作的内容,并将其作为 JSON 返回到 Angular。我觉得 ResponseEntity 或 RestControllerAdvice 可能是答案,只是不确定是否是准确的最佳实施方式。
【问题讨论】:
标签: mysql angular spring-boot maven error-handling