简体   繁体   中英

How to send customise response message when any constraint violation error occured in spring boot

Let's assume, I have one class name 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;

}

Now if any duplicate email address receives by the database then it'll show an error. But I want to pass that error message or customize the error message in Api Response.

Please let me know if you have any idea about it.

You can use @ControllerAdvice to handle errors during HTTP call

@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());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM