简体   繁体   English

用于在 Spring Boot 中进行验证的自定义 ExceptionHandler?

[英]Custom ExceptionHandler for validation in Spring Boot?

In a Spring Boot app, I implemented a custom exception handling in my Spring Boot app as in this example and throw NoSuchElementFoundException without any problem as shown below:在一个 Spring Boot 应用程序中,我在我的 Spring Boot 应用程序中实现了一个自定义异常处理,如例所示,并抛出NoSuchElementFoundException没有任何问题,如下所示:

public EmployeeDto findByEmail(String email) {
    return employeeRepository.findByEmail(email)
            .map(EmployeeDto::new)
            .orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND));
}

However, I also added another custom exception class and define its handler in my Global class as shown below:但是,我还添加了另一个自定义异常类,并在我的 Global 类中定义了它的处理程序,如下所示:

@ExceptionHandler(NotValidFormatException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public ResponseEntity<Object> handleNotValidFormatException(NotValidFormatException ex, WebRequest request) {
    log.error("Invalid format. Only csv files are allowed.", ex);
    return buildErrorResponse(ex, HttpStatus.UNPROCESSABLE_ENTITY, request);
}

Here is my service method where I throw this exception if the file is not valid type:这是我的服务方法,如果文件不是有效类型,我将在其中抛出此异常:

public void create(MultipartFile file) throws Exception {
    if (CsvHelper.hasCsvFormat(file)) {
        throw new NotValidFormatException("Not valid type");
    }
    // ...
}

Now, I am not sure where I should check the validity:现在,我不确定应该在哪里检查有效性:

Should I just check it via a static method in my Util class?我应该通过我的 Util 类中的静态方法来检查它吗?

or implement a custom validator as mentioned here ?或实施此处提到的自定义验证器? In this case I am not sure if I still need my custom exception class.在这种情况下,我不确定是否还需要自定义异常类。 Any idea?任何想法?

Creating a validator is almost always a good idea, because it is simpler to unit test this service method.创建验证器几乎总是一个好主意,因为对这个服务方法进行单元测试更简单。

public void create(MultipartFile file) throws Exception {
    fileValidator.validate(file);
}
  1. Create unit test for FileValidatorFileValidator创建单元测试
  2. Mock fileValidator.validate(eq(file)) method to throw NotValidFormatException and assert that you have an exception when call create(file) .模拟fileValidator.validate(eq(file))方法以抛出NotValidFormatException并在调用create(file)时断言您有异常。
  3. Do nothing with fileValidator for other test methods for the service.对于服务的其他测试方法,不使用fileValidator执行任何操作。

Keep in mind that sometimes it is better not to use a validator to keep code simpler.请记住,有时最好不要使用验证器来简化代码。 For example, if you need to validate an id .例如,如果您需要验证id

Notes笔记

I prefer not to create an exception for each validation check.我不想为每个验证检查创建异常。 Just to use a common class for all validation errors.只是为了对所有验证错误使用一个通用类。 You can return multiple validation errors with such approach.您可以使用这种方法返回多个验证错误。

public class ValidationException extends ServiceException {

    public ValidationException(ErrorResponseItem item) {
        this(Collections.singletonList(item));
    }

    public ValidationException(List<ErrorResponseItem> items) {
        super(HttpStatus.UNPROCESSABLE_ENTITY, items);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM