hop
hop

Reputation: 2558

Throw 404 and redirect to a custom error page in Spring

I have the below piece of exception handler that redirects to "notfound" page when the resource is not found. But, in the apache logs, I am not seeing 404 error code. Is there any way to get a 404 error thrown by this exception handler?

@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
    request.setAttribute("message", e.getMessage());
    return "forward:notfoundpage";
}

Upvotes: 1

Views: 8394

Answers (2)

Alex Chernyshev
Alex Chernyshev

Reputation: 1745

Yes:

@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request, final HttpServletResponse response)
{   response.setStatus(404);
    request.setAttribute("message", e.getMessage());
    return "forward:notfoundpage";
}

another way is to mark your exception with special annotation:

 @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
    public class UnknownIdentifierException extends RuntimeException {
        // ...
    }

and one more way is to specify error code in annotation on handler itself:

  @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Data integrity violation")  
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
///

Here is the long blog post on topic: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Upvotes: 2

Neil McGuigan
Neil McGuigan

Reputation: 48236

Preferably, you should not redirect to an error page, but simply display an error message and set an error HTTP status code. You would do this by throwing an exception in your controller handler method.

You need to make a class then throw it (though perhaps you've already done this with your UnknownIdentifierException):

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {}

In your controller handler method:

throw new ResourceNotFoundException();

To set a page to display on an exception, in web.xml:

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

Upvotes: 0

Related Questions