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?