2

I think there is a better way to do this in Spring boot/hibernate. There are many tables and I don't want to add User Defined model for every table: here

I have an entity

@Entity
public class Item extends ExtraEntity {
       @NotEmpty(message = "Item code can not be Empty !")
       @Column(unique = true)
       private String code;
       @NotEmpty (message = "Item name can not be Empty !")
       @Column(unique = true)
       private String name;
}

How do I send a custom message for my REST APIs stating if code is duplicate or name is duplicate?

Suraj Regmi
  • 253
  • 3
  • 11

1 Answers1

2

In the outermost layer, catch the exception as follows:

try {
    newEntity = ourService.createUpdate(entity);
} catch (JpaSystemException jpae) {
    if (jpae.getCause().getCause() instanceof ConstraintViolationException) {
        if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_CODE_01")){
            throw new DuplicatedCodeException("Message",jpae);
        } else if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_NAME_01")){
            throw new DuplicatedNameException("Message",jpae);
        }
    }
}

Create a custom exception for each unique key like this:

public class DuplicatedNameException extends Exception {

    public DuplicatedNameException(String message){
        super(message);
    }

    public DuplicatedNameException(String message, Throwable anException){
        super(message, anException);
    }
}

Define an exception handler that extends from the ResponseEntityExceptionHandler class and treats the received exception as follows:

@ExceptionHandler({ DuplicatedNameException.class })
    public ResponseEntity<Object> handleDuplicatedNameException(Exception anException, WebRequest request) {

    [...]

    return new ResponseEntity<>(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}

This HTTPStatus is the one that you should check in the web layer to show the error message

JLazar0
  • 1,257
  • 1
  • 11
  • 22