簡體   English   中英

如何在 spring 引導中發生任何約束違反錯誤時發送自定義響應消息

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM