Jack
Jack

Reputation: 6650

How to globally handle 404 exception by returning a customized error page in Spring MVC?

I need to return a customized error page for HTTP 404, but the code does not work. I already read the stackflow 1,2, 3 and different online + articles but my case is quite different with those or at least I can not figure out the issue.

HTTP Status 404 -

type Status report

message

description The requested resource is not available.

For example, it is suggested to use an action name in web.xml to handle the exception, it might work but I think is not a good method of doing it.

I used following combinations:

1)

@Controller   //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

2)
 @Controller   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(HttpStatus.NOT_FOUND) //for method

4)
 @ControllerAdvice   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

Code

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public String handleBadRequest(Exception exception) {
          return "error404";
    }
}

Upvotes: 2

Views: 2397

Answers (3)

M4ver1k
M4ver1k

Reputation: 1575

You can add the following in your web.xml to display an error page on 404. It will display 404.jsp page in views folder inside WEB-INF folder.

 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>

Upvotes: 0

Mithun
Mithun

Reputation: 8077

DispatcherServlet does not throw an exception by default, if it does not find the handler to process the request. So you need to explicitly activate it as below:

In web.xml:

<servlet>
    <servlet-name>mvc-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>
    <load-on-startup>1</load-on-startup>
</servlet>

If you are using annotation based configuration:

dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

In the controller advice class:

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
    return "errorPage";
}

Upvotes: 2

Daniel Newtown
Daniel Newtown

Reputation: 2933

You can use the @ResponseStatus annotation at the class level. At least it works for me.

@Controller
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class GlobalExceptionHandler {
  ....  
}

Upvotes: 1

Related Questions