Kamil Nękanowicz
Kamil Nękanowicz

Reputation: 6532

How to handle exception with Spring/JPA?

I want to handle this exception:

try {
      save = usersRepository.save(user);
}
catch (Exception gottaCatchEmAll){
      System.out.println("got it");
}

in logs I see:

Cannot add or update a child row: a foreign key constraint fails

How can I catch it?

Upvotes: 0

Views: 2262

Answers (1)

Vaelyr
Vaelyr

Reputation: 3176

I would suggest writing advice handler class for dealing with any exceptions. For example I assume your exception is of type DataIntegrityViolationException. That will be wrapped in some kind of DTO which can be returned to front-end or do what you like with it.

@ControllerAdvice
public class ExceptionHandler {

  @ExceptionHandler(DataIntegrityViolationException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ResponseBody
  public ErrorDto processConstraintError(DataIntegrityViolationException ex) {
    return new ErrorDto(ex.getMessage());
  }

}

No need to try-catch anything from JPA.

Upvotes: 1

Related Questions