For my file (csv) upload endpoint, I check the file type using a method in my CsvHelper class:
private static String[] TYPES = {"text/csv", "application/vnd.ms-excel"};
public static boolean hasCsvFormat(MultipartFile file) {
return Arrays.stream(TYPES).anyMatch(file.getContentType()::equals);
}
And call it from service as shown below:
public void create(MultipartFile file) throws Exception {
if (!CsvHelper.hasCsvFormat(file)) {
throw new NotValidFormatException(...);
}
// ...
}
I created a custom exception for this called NotValidFormatException using @ControllerAdvice, but I am not sure if it is the most proper way for this.
My questions:
1. Should I create custom exception or custom validator as mentioned on this? But as I have not a model field, I need to use @Valid on the request and not sure if I can use that approach to verify file type (by calling my hasCsvFormat() method.
2. I used this approach for creating custom exception handling. If I wanted to use that approach for this scenario, should I create a separate class (e.g. NotValidFormatException) like NoSuchElementFoundException on that example? Or should I include a new exception method to the GlobalExceptionHandler class as a common exception type?
CodePudding user response:
Based on your requirement, option number 2 is more suitable from my perspective.
You can create separate class for NotValidFormatException , annotate with ResponseStatus of your need & extend it with RuntimeException.
Now, your GlobalExceptionHandler is general purpose handler which perform actions once specific exception is thrown.
So you have to create method which should annotate with @ExceptionHandler(NotValidFormatException.class) in GlobalExceptionHandler .
Benefits of having separate class for NotValidFormatException is you can customize error message, can perform more operation within methods of that class.
If your requirement is minimal(like logging & returning response etc.) , then I would suggest to have only single ExceptionHandler method in GlobalExceptionHandler which will handle most of exceptions i.e. logging & returning response.
