Skip to content

Instantly share code, notes, and snippets.

@Cepr0
Created February 21, 2019 14:43
Show Gist options
  • Save Cepr0/07e497ea193990f7a48432f87c363ee3 to your computer and use it in GitHub Desktop.
Save Cepr0/07e497ea193990f7a48432f87c363ee3 to your computer and use it in GitHub Desktop.
DataIntegrityViolationException handling
@Order(HIGHEST_PRECEDENCE)
@ExceptionHandler(DataIntegrityViolationException.class)
ResponseEntity<?> handleException(DataIntegrityViolationException ex, ServletWebRequest request) {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
String messageCode = message.replaceFirst(".*\"(.*)\"\\s(.|\\s)*", "$1"); // replace "bla-bla\"code\"\nbla-bla" to "code"
var errorMessage = ApiErrorMessage.badRequest(messageProvider.getLocalizedMessage(messageCode));
return super.handleExceptionInternal(ex, errorMessage, null, errorMessage.getHttpStatus(), request);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment