[英]Trying to get Spring Boot app to send an error response message when request does not have "Content-type" HTTP request header
[英]How to send customise response message when any constraint violation error occured in spring boot
假设,我有一个 class 名字的学生
@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;
}
现在,如果数据库收到任何重复的 email 地址,则会显示错误。 但我想在 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.