11

In my controller I do a permissions check to see if the user can do the certain action. If they can't, I'd like to return a 404.

How do I tell Spring to return a 404?

3
  • 5
    See stackoverflow.com/questions/2066946/… Commented Feb 10, 2010 at 17:19
  • @axtavt The answer on this page is what I used. Thanks Commented Feb 12, 2010 at 18:40
  • 2
    You should really respond with a 403.. Commented Sep 29, 2011 at 1:38

2 Answers 2

21

You can throw an exception and handle it in a controller-level method:

@Controller
public class MyController {

    @ResponseStatus(NOT_FOUND)
    @ExceptionHandler({UnauthorizedException.class})
    public void handle() {
        // ...
    }
}

If any controller method throw a UnauthorizedException., the above handler method will be invoked to handle it and return a 404 error.

Sign up to request clarification or add additional context in comments.

2 Comments

Really slick way of handling this.
On newer version of Spring, you can just throw NoSuchRequestHandlingMethodException in your controller I comment here because it still appears in google first page
-3

You can derive your exception from HttpException and path 404 code to base constructor:

public class MyNotFoundException : HttpException
{
    public MyNotFoundException(string message, Exception inner)
        : base(404, message, inner)
    {
    }
}

2 Comments

I'm guessing that's Spring.NET - there's no HttpException class in Spring.
That syntax to call the superclass constructor is C# too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.