我使用@ExceptionHandler
来处理我的网络应用引发的异常,在我的情况下,我的应用返回JSON
响应HTTP status
,以回复客户端的错误。
但是,我试图弄清楚如何处理error 404
以返回类似的JSON响应,就像@ExceptionHandler
更新
我的意思是,当访问不存在的URL时
答案 0 :(得分:41)
我使用spring 4.0和java配置。我的工作代码是:
@ControllerAdvice
public class MyExceptionController {
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handleError404(HttpServletRequest request, Exception e) {
ModelAndView mav = new ModelAndView("/404");
mav.addObject("exception", e);
//mav.addObject("errorcode", "404");
return mav;
}
}
在JSP中:
<div class="http-error-container">
<h1>HTTP Status 404 - Page Not Found</h1>
<p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
</div>
对于Init param config:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
或通过xml:
<servlet>
<servlet-name>rest-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>
</servlet>
答案 1 :(得分:5)
春天&gt; 3.0使用@ResponseStatus
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class MyController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// do some stuff
}
else {
throw new ResourceNotFoundException();
}
}
}
答案 2 :(得分:4)
最简单的方法是使用以下内容:
@ExceptionHandler(Throwable.class)
public String handleAnyException(Throwable ex, HttpServletRequest request) {
return ClassUtils.getShortName(ex.getClass());
}
如果URL在DispatcherServlet的范围内,则此方法将捕获由错误输入或其他任何内容引起的任何404,但如果键入的URL超出DispatcherServlet的URL映射,则必须使用:
<error-page>
<exception-type>404</exception-type>
<location>/404error.html</location>
</error-page>
或
为DispatcherServlet映射URL提供“/”映射,以便处理特定服务器实例的所有映射。
答案 3 :(得分:3)
public final class ResourceNotFoundException extends RuntimeException {
}
@ControllerAdvice
public class AppExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFound() {
return "404";
}
}
只需定义一个Exception,一个ExceptionHandler,从业务代码控制器中抛出Exception。
答案 4 :(得分:1)
您可以使用servlet标准方式来处理404错误。在web.xml
<error-page>
<exception-type>404</exception-type>
<location>/404error.html</location>
</error-page>