如何在春季启动中发生任何违反约束的错误时发送自定义响应消息



假设我有一个类名Student

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(
name = "tbl_student",
uniqueConstraints = @UniqueConstraint(
name = "emailid_unique",
columnNames = "email_address"
)
)
public class Student {
@Id
@GeneratedValue(
strategy = GenerationType.AUTO)
private Long studentId;
private String firstName;
private String lastName;
@Column(
name = "email_address",
nullable = false
)
private String emailId;
}

现在,如果数据库收到任何重复的电子邮件地址,则会显示错误。但我想在Api响应中传递错误消息或自定义错误消息。

如果你对此有任何想法,请告诉我。

您可以使用@ControllerAdvice来处理HTTP调用期间的错误

@Component("MyExceptionHandler")
public class ExceptionHandlerAdvice {
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(CONFLICT)
@ResponseBody
public SomeErrorDTO handle ConstraintViolationException(ConstraintViolationException e) {
log.warn("Encountered ConstraintViolationException: ", e);
return new SomeErrorDTO("Duplicate ....", e.getMessage());
}

相关内容

最新更新