Skip to content

Spring Boot: Custom exception adds prefix to the exception message

In a Spring Boot app, I created a custom GlobalExceptionHandler and add the following method to handle ConstraintViolationException for invalid file type during upload process:

public ResponseEntity<Object> handleConstraintViolationException(
                              ConstraintViolationException ex, 
                              WebRequest request) {
    log.error("Invalid file type.", ex);
    return buildErrorResponse(ex, HttpStatus.UNPROCESSABLE_ENTITY, request);

My buildErrorResponse works correctly and build proper responses for other handle methods. However, It adds “uploadFile.file:” prefix to my error message.

My questions:

  1. Is there any problem with my handleConstraintViolationException implementation? If not, how can I fix that problem?

  2. I think there is no need to create custom exception class as shown below for the exceptions that is already defined in javax.validation like ConstraintViolationException. Is that true?

Note: If you need to have a look at my GlobalExceptionHandler, it is something like on this GitHub.



Answer For Question 1: Your implementation not wrong but have some missing properties. For best practice to my opinion you can create a class to use it for error response which can contains like statusCode,timestamp,message,description. You can use method like this in your handleConstraintViolationException method:

private ResponseEntity<ErrorMessage>generateErrorMessage(ConstraintViolationException ex, WebRequest request){
    ErrorMessage errorMessage = new ErrorMessage.ErrorMessageBuilder()
            .timeStamp(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(
    return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);