简体   繁体   中英

Spring ExceptionHandlerController for catching errors is not working

I am trying to create a controller so that when a user goes to a non-existing URL, he/she will be mapped to a custom error page "error.jsp".

Currently, my Exception Handler Controller looks as followed:

@ControllerAdvice 
public class ExceptionHandlerController {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);

    @ExceptionHandler(value = {Exception.class, RuntimeException.class})
    public String defaultErrorHandler(Exception e) {
        logger.error("Unhandled exception: ", e);
        return "error";
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle(Exception e) {
        logger.error("No handler found!", e);
        return "error";
    }
}

However, when I run my web app and visit a nonexisting URL, I get redirected to the default browser page saying '404 this page cannot be page.

Does anyone have any thoughts or suggestions as to why this is not working?

From the javaDoc of NoHandlerFoundException

By default when the DispatcherServlet can't find a handler for a request it sends a 404 response. However if its property "throwExceptionIfNoHandlerFound" is set to true this exception is raised and may be handled with a configured HandlerExceptionResolver.

To solve this, You need to make sure you did these 2 things .

  1. Creating SimpleMappingExceptionResolver and registering as a bean

    @Bean HandlerExceptionResolver customExceptionResolver () { SimpleMappingExceptionResolver s = new SimpleMappingExceptionResolver(); Properties p = new Properties(); //mapping spring internal error NoHandlerFoundException to a view name. p.setProperty(NoHandlerFoundException.class.getName(), "error-page"); s.setExceptionMappings(p); //uncomment following line if we want to send code other than default 200 //s.addStatusCode("error-page", HttpStatus.NOT_FOUND.value());

      //This resolver will be processed before default ones s.setOrder(Ordered.HIGHEST_PRECEDENCE); return s; 

    }


  1. Set setThrowExceptionIfNoHandlerFound as true in your dispatcherServlet.

p

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

  ....
  ......

  @Override
  protected FrameworkServlet createDispatcherServlet (WebApplicationContext wac) {
      DispatcherServlet ds = new DispatcherServlet(wac);
      //setting this flag to true will throw NoHandlerFoundException instead of 404 page
      ds.setThrowExceptionIfNoHandlerFound(true);
      return ds;
  }

}

Refer complete example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM