Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

421
Vistas
java - throwExceptionIfNoHandlerFound not works

I'm trying to handle 404 error using an @ControllerAdvice in a Spring MVC application totally configured using Java configuration.

Here you have my conf:

public class WebAppInitializer implements WebApplicationInitializer
{

    @Override
    public void onStartup(ServletContext container)
    {

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(WebMvcConfig.class);

        dispatcherServlet.setServletContext(container);
        dispatcherServlet.refresh();

        CookieHelper cookie = (CookieHelper) dispatcherServlet.getBean("cookie");
        final Gson gson = (Gson) dispatcherServlet.getBean("gson");

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
        dispatcher.addMapping("/");
        dispatcher.setLoadOnStartup(1);
        dispatcher.setInitParameter("throwExceptionIfNoHandlerFound", "true");

        FilterRegistration.Dynamic filter = container.addFilter("BaseFilter", new BaseFilter(cookie, gson));
        filter.setInitParameter("forceEncoding", "true");
        filter.addMappingForUrlPatterns(null, true, "/coolers/*");
        filter.addMappingForUrlPatterns(null, true, "/hothouses/*");
        filter.addMappingForUrlPatterns(null, true, "/lang/*");
        filter.addMappingForUrlPatterns(null, true, "/organizations/*");
        filter.addMappingForUrlPatterns(null, true, "/reworks/*");
        filter.addMappingForUrlPatterns(null, true, "/select/*");
        filter.addMappingForUrlPatterns(null, true, "/volumes/*");
    }

}

and my GlobalExceptionHandlerController:

@ControllerAdvice
public class GlobalExceptionHandlerController 
{
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handle() {
      System.out.println("test test test test");
      return "error/index";
    }
} 

NoHandlerFoundException not firing?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I had the same issue, got it resolved. Below given steps to solve the same.

  1. Create a class GlobalExceptionHandler annotated with @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler 
{
    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFoundError(Exception ex) 
    {
        return "redirect:/yourCustom404page";
    }
}
  1. By default, when a page/resource does not exist the servlet container will render a default 404 page. If you want a custom 404 response then you need to tell DispatcherServlet to throw the exception if no handler is found. We can do this by setting the throwExceptionIfNoHandlerFound servlet initialization parameter to true

a. If spring-mvc java based configuration is

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    ...

    @Override
    protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) 
    {
        final DispatcherServlet servlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
        servlet.setThrowExceptionIfNoHandlerFound(true);
        return servlet;
    }

}

b. if spring-mvc xml based configuration, initialize your dispatcher servlet like this

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

c. if spring-boot
spring.resources.add-mappings=false in your application.properties or yaml file.

Hope it helps

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda