Search code examples
spring-bootspring-mvcthymeleaf

catch 404 error spring boot to return custom html


How can i catch 404 error in application and render a custom html like index.html? i don't want to use a page inside the /error folder.

for example if i'm asking for http://localhost:8080/test and there is no mapping for test, my application should render index.html inside the /resources/template folder

Thanks

****EDIT****

kinda solved this way, the bad thing is that i can't change the path for request mapping even changing the getErrorPath return value.

@Controller
public class MyCustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        return "globalerrorview";
    }

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

Solution

  • There are many ways to achieve the custom error page. One easy way is using /resources/public/error/404.html which is not desired in your case.

    Option:1 Could you try configuring ControllerAdvice.

    application.properties
        spring.mvc.throw-exception-if-no-handler-found=true
    ----------------------
    @ControllerAdvice
    class YourApplicationExceptionHandler {
    
        @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
        @ExceptionHandler(NoHandlerFoundException.class)
        public ModelAndView handleNoHandlerFoundException() {
            return new ModelAndView("viewName");
        }
    } 
    

    Option 2: If you have any other path defined for the error you can simply change the /error path. In your Controller define the corresponding path mapping and route to the custom view.

    server.error.path=/yourcustomerrorpath
    
    

    Option 3: Using ErrorController

    @Controller
    public class MyCustomErrorController implements ErrorController {
    
        @RequestMapping("/error")
        public String handleError() {
            return "globalerrorview";
        }
    
        @Override
        public String getErrorPath() {
            return "/error";
        }
    }