Home > OS >  Spring Boot: Custom exception adds prefix to the exception message
Spring Boot: Custom exception adds prefix to the exception message

Time:07-24

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:

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
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.

CodePudding user response:

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 ResponseEntitygenerateErrorMessage(ConstraintViolationException ex, WebRequest request){ ErrorMessage errorMessage = new ErrorMessage.ErrorMessageBuilder() .statusCode(HttpStatus.BAD_REQUEST.value()) .timeStamp(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())) .message(ex.getMessage()) .description(request.getDescription(false)) .build(); return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); }

  • Related