1

I use spring MVC in my web application. I have been trying various options to return custom error pages for the various exceptions thrown in my application. I have managed to do that using the @ControllerAdvice annotation. My global exception handler class would be as follow:

import org.apache.velocity.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionControllerAdvice
{

    private static final Logger logger  = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    @ExceptionHandler(Exception.class)
    public String exception(Exception e) 
    {
        logger.error(e.toString());
        return "exceptionPage";
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleMissingParameter() 
    {
        return "exceptionPage";
    }
}

But the trouble I am facing is with the HTTP 404 error. Is there any way I can handle the HTTP status errors also using this annotation. I also use Apache tiles and I render my pages using tiles and I use ftl pages.

  • http://stackoverflow.com/questions/21061638/spring-mvc-how-to-return-custom-404-errorpages ? – Brian Kates Jan 13 '16 at 16:00
  • @BrianKates, I have updated the question with what I have tried after following your suggestion, but still I am redirected to the tomcat error page –  Jan 13 '16 at 17:27
  • You could also put it in the web.xml: http://stackoverflow.com/questions/7066192/how-to-specify-the-default-error-page-in-web-xml – Brian Kates Jan 13 '16 at 18:52

1 Answers1

1

had the same issue and couldn't seem to get the answers anywhere then i found this blog http://nixmash.com/java/custom-404-exception-handling-in-spring-mvc/

add the following code to your controller:

@RequestMapping(value ={ "{path:(?!resources|static).*$}","{path:(?!resources|static)*$}/**" }, headers = "Accept=text/html")

public void unknown() throws Exception{
    throw new Exception();
}
}

Any path that contains "resources" or "static" would not return an error page -this is to prevent things like images from not showing ,but any other page that is not mapped would raise an error page

Essentially this would return a 404 error page(exceptionPage) that you have configured in your controller advice