gpt4 book ai didi

mysql - Spring Boot Maven和MySQL错误处理

转载 作者:行者123 更新时间:2023-12-03 08:40:07 25 4
gpt4 key购买 nike

我有以下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)
}

Angular 响应如下所示
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)正常工作的内容,并将其返回为angular作为JSON。我觉得像ResponseEntity或RestControllerAdvice可能是答案,只是不确定如果准确的话最好的实现方式。

最佳答案

您已经有了答案。

I feel like ResponseEntity or RestControllerAdvice might be the answer



您只能使用自己的格式创建dto响应。然后将其放在ResponseEntity中,以防万一出错。

关于mysql - Spring Boot Maven和MySQL错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62453410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com