How to override default Tomcat 404 not found html page in Spring Boot 3.2?

I’m working on a Spring Boot 3.2 application and have set a custom context path (/api). I want to replace the default HTML error responses from Tomcat with JSON responses, especially for 404 errors. However, I am encountering difficulties handling 404 errors that occur outside of the context path.

Global Exception Handler

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleGlobalException(Exception ex) {
        log.error("An error occurred: {}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(false, ex.getMessage()));
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public ResponseEntity<?> handleNoResourceFoundException(NoResourceFoundException ignored) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

Security Configuration

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf(AbstractHttpConfigurer::disable)
            .cors(Customizer.withDefaults())
            .exceptionHandling(exception ->
                    exception.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.NOT_FOUND)))
            .authorizeHttpRequests(auth -> auth.requestMatchers(PERMIT_ALL_URL_PATTERNS.toArray(new String[0]))
                    .permitAll()
                    .anyRequest()
                    .authenticated())
            .sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
            .formLogin(AbstractHttpConfigurer::disable)
            .httpBasic(AbstractHttpConfigurer::disable)
            .oauth2Login(loginConfigurer -> loginConfigurer
                    .userInfoEndpoint(endpointConfig -> endpointConfig.userService(customOAuth2UserService))
                    .successHandler(oAuth2AuthenticationSuccessHandler)
                    .authorizationEndpoint(authEndPoint ->
                            authEndPoint.authorizationRequestRepository(authorizationRequestRepository))
                    .failureHandler(oAuth2AuthenticationFailureHandler))
            .build();
}

Observed Issues:

  • For URLs within the context path, everything is handled as expected.
  • For URLs outside the context path, Tomcat’s default HTML error pages are returned.

What I tried:

  • spring.mvc.throw-exception-if-no-handler-found – it’s deprecated, IIUC NoHandlerFoundException is no longer thrown in new Spring Boot versions
  • error.whitelabel.enabled=false

CustomErrorController

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Map<String, String>> handleError(HttpServletRequest request) {
        Object status = request.getAttribute("javax.servlet.error.status_code");
        HttpStatus httpStatus = HttpStatus.valueOf(Integer.parseInt(status.toString()));

        Map<String, String> response = new HashMap<>();
        response.put("error", httpStatus.getReasonPhrase());
        response.put("message", "The requested URL was not found on this server.");

        return new ResponseEntity<>(response, httpStatus);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

Custom ErrorReportValve

@Slf4j
public class CustomTomcatErrorValve extends ErrorReportValve {

    @Override
    protected void report(Request request, Response response, Throwable throwable) {

        if (!response.setErrorReported()) return;

        if (log.isDebugEnabled())
            log.debug(
                    "Tomcat failed to prepare the request for spring (set response code to {}).",
                    response.getStatus(),
                    throwable);

        HttpStatus status = HttpStatus.valueOf(response.getStatus());

        try {

            response.setContentType("application/problem+json");
            Writer writer = response.getReporter();
            writer.write(String.format(
                    """
                    {
                        "title": "%s",
                        "status": %d
                    }""",
                    status.getReasonPhrase(), status.value()));
            response.finishResponse();
        } catch (IOException ignored) {
        }
    }
}

Exception handler filter:

@Slf4j
@Component
public class UnhandledExceptionHandlerFilter extends OncePerRequestFilter {

    private static class StatusCodeCaptureWrapper extends HttpServletResponseWrapper {

        @Getter
        private Integer statusCode;

        @Getter
        private final HttpServletRequest request;

        @Getter
        private final HttpServletResponse response;

        public StatusCodeCaptureWrapper(HttpServletRequest request, HttpServletResponse response) {
            super(response);
            this.request = request;
            this.response = response;
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException {
        StatusCodeCaptureWrapper responseWrapper = new StatusCodeCaptureWrapper(request, response);
        Throwable exception = null;

        try {
            chain.doFilter(request, responseWrapper);
        } catch (ServletException e) {
            exception = e.getRootCause();
        } catch (Throwable e) {
            exception = e;
        }

        if (exception != null
                && !"ClientAbortException".equals(exception.getClass().getSimpleName())) {
            ensureErrorStatusCodeSet(responseWrapper);
            response.setStatus(responseWrapper.getStatusCode());
            handleException(request, response, responseWrapper.getStatusCode(), exception);
        }

        response.flushBuffer();
    }

    private void ensureErrorStatusCodeSet(StatusCodeCaptureWrapper responseWrapper) {
        if (responseWrapper.getStatusCode() == null) {
            responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void handleException(
            HttpServletRequest request, HttpServletResponse response, int statusCode, Throwable throwable)
            throws IOException {
        log.error("Sending error response status {} for {} because of", statusCode, request.getRequestURI(), throwable);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Map<String, String> responseBody = new HashMap<>();
        responseBody.put("error", HttpStatus.valueOf(statusCode).getReasonPhrase());
        responseBody.put("message", throwable.getMessage());
        response.getWriter().write(new ObjectMapper().writeValueAsString(responseBody));
    }
}

How can I configure Spring Boot 3.2 to always return JSON error responses, especially for 404 errors, instead of Tomcat’s default HTML error pages, even for URLs outside of the context path?

Any guidance or solutions would be greatly appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật