spring filter exception handling

  1. Create a custom exception class:
public class CustomException extends RuntimeException {
    // Constructor and custom logic for the exception
  1. Create a custom exception handler:
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    public final ResponseEntity<Object> handleCustomException(CustomException ex, WebRequest request) {
        // Create a custom error response
        ErrorResponse errorResponse = new ErrorResponse("Custom error message", HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);

    // Handle other exceptions if needed
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // Create a custom error response for internal exceptions
        ErrorResponse errorResponse = new ErrorResponse("Internal error occurred", HttpStatus.INTERNAL_SERVER_ERROR.value());
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
  1. Create a filter for exception handling:
public class ExceptionHandlingFilter extends OncePerRequestFilter {

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (CustomException ex) {
            // Handle custom exception and set response accordingly
            response.getWriter().write("Custom error message");
        } catch (Exception ex) {
            // Handle other exceptions and set response accordingly
            response.getWriter().write("Internal error occurred");
  1. Register the filter in your Spring configuration:
public class AppConfig extends WebMvcConfigurerAdapter {

    public FilterRegistrationBean<ExceptionHandlingFilter> exceptionHandlingFilter() {
        FilterRegistrationBean<ExceptionHandlingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new ExceptionHandlingFilter());
        registrationBean.addUrlPatterns("/api/*"); // Set the URL patterns to apply the filter
        return registrationBean;

Note: Ensure that you adapt the code according to your project structure and requirements.