Spring filter throws custom exception

I have a controller tip that handles all validation exceptions thrown by my application as shown 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 opinion, I would like to create a filter that will do the validation for every request and throw a custom exception if necessary. But the point is, I cannot pick a custom exception like 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 a ValidationErrorException in this case or are there other better ways to handle such a task.

+1


source to share


1 answer


Checks are usually performed on request objects, which are usually available at the level Controller

after they are transformed

from the request format to the server processing format. for example JSON for Java.

So the check should be done or run at the level Controller

after reaching the request, completing the whole chain filter

.

Any validation exception thrown later can be handled in your next 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())); 
    }
}

      



Very important one

goals filters

:

To intercept requests from the client before they back end.

Thus, filters do not actually have an actual resource to be verified. They are available as soon as the control reaches the value component

, and in your case that is Controller

.

So the best approach is to skip checking resource

on components filter

.

+2


source







All Articles