开发者

In a web MVC framework, who has the responsibility to show 404 page?

In a web MVC model, which class/object has the responsibility/function to call 404 page?开发者_JS百科 Why does it has the responsibility? I think it's the Router, but I'm asking just in case.

$router->show_404("Unable to find controller.");

Also, should a 404 page be a view or just a template? What's the standard practice here?

-- Update, makes things much clearer --

If for example, we agree that the the Router class holds the function/responsibility to call 404 page, should we then inject Router object to the controller we instantiated so that each controller can use the Router object to call 404s? Or should I create a custom class built to display 'special pages' like Error/404s?

Thanks for the answer.


Depends on the situation.

If it's due to an invalid route, then it can either be handled by the router itself or you can have a default route which points to a 404 handler.

If it's due to a valid route receiving invalid data (/user/JohnDoe, but John Doe isn't known to the system), then the 404 would have to be initiated by the handler for that route.

Once the 404 is triggered, I tend to prefer light, fast pages reporting it, but there are plenty of sites out there which will, e.g., do an approximate-match search and return a list of "did you mean one of these things?" I'm not sure which way I would call "standard practice" in either case, unless you're talking about REST APIs, which would normally send a minimal response, since they're aimed at machine-readability, so there's not a lot of point in asking a question that only a human could answer.


I prefer something like this in the "driver":

try
{
  $router->handleRequest($request);
}
catch (Exception $e)
{
  $view = new View('error');
  echo $view;
}

A 404 is just another exception handled by the catch block. You could always have a specific 404 exception if you want to do something special with it. Or you could have a generic "http exception" that includes some status code that would indicate which template to use.


It is the responsibility of the View, to report the error. And view code need to be designed accordingly to report the meaningful error messages

<web-app ...> 

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

</web-app>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜