Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

423
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda