带弹簧控制器的手柄错误 404

2022-09-02 11:17:28

我用于处理 Web 应用引发的异常,在我的情况下,我的应用向客户端返回错误响应。@ExceptionHandlerJSONHTTP status

但是,我正在尝试弄清楚如何处理返回类似的JSON响应,就像由error 404@ExceptionHandler

更新:

我的意思是,当访问不存在的URL时


答案 1

我使用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 参数配置:

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>

另请参阅: 弹簧 MVC 弹簧安全和错误处理


答案 2

有弹簧>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(); 
        }
    }
}

推荐