简体   繁体   English

Spring过滤器抛出自定义异常

[英]Spring filter throws custom exception

I have a controller advice that handle all validation exception thrown by my application as below. 我有一个控制器建议,处理我的应用程序抛出的所有验证异常,如下所示。

@RestControllerAdvice
public class RestApiExceptionController {

    @ExceptionHandler(ValidationErrorException.class)
    public ResponseEntity<?> appNotFoundException(ValidationErrorException exception) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new ErrorResponse(exception.getErrorCode(), exception.getMessage())); 
    }
}

In my way, I would like to create a filter that will make validation to every request and throw custom exception when necessary. 在我的方式中,我想创建一个过滤器,它将对每个请求进行验证,并在必要时抛出自定义异常。 But the thing is that I cannot throw custom exception as show below. 但问题是我不能抛出自定义异常,如下所示。

public class ValidationFilter implements Filter {
    ...
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        throw new ValidationErrorException(); // This is impossible
    }
    ...
}

How can I throw the ValidationErrorException in this case or there are other better ways to handle such task. 在这种情况下如何抛出ValidationErrorException,或者还有其他更好的方法来处理此类任务。

The validations are generally done on the request objects which are in general available in Controller layer after they are transformed from request format to server processing format. 该验证是在它们是一般可以在请求的对象通常做Controller层它们之后transformed从请求格式到服务器处理的格式。 eg JSON to Java object. 例如JSON到Java对象。

So the validation should be performed or triggered on Controller layer once the request is reached by completing your entire filter chaining. 因此,一旦通过完成整个filter链接到达请求,就应该在Controller层上执行或触发验证。

Any validation exception thrown then later on can be handled in your following handler, 稍后抛出的任何验证异常都可以在您的后续处理程序中处理,

@RestControllerAdvice
public class RestApiExceptionController {

    @ExceptionHandler(ValidationErrorException.class)
    public ResponseEntity<?> appNotFoundException(ValidationErrorException exception) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new ErrorResponse(exception.getErrorCode(), exception.getMessage())); 
    }
}

The very much one of the purpose of filters is, 在很多one的目的filters是,

To intercept requests from a client before they access a resource at back end. 在客户端访问后端资源之前拦截客户端的请求。

So filters in real don't have the actual resource yet to be validated. 因此,实际的过滤器还没有待验证的实际资源。 They are available once the control reaches to correct component and in your case it is Controller . 一旦控件到达正确的component ,它们就可用,在您的情况下,它是Controller

So better approach is not to do any resource based validations at filter components. 因此,更好的方法是不在filter组件上进行任何基于resource的验证。

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

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