zoukankan      html  css  js  c++  java
  • Springboot 统一异常处理

    针对 404 其实 springmvc 提供了2种方式     404 是比较特殊的   

    1.先设置dispatcherServlet

    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
    ServletRegistrationBean registration = new ServletRegistrationBean(
    dispatcherServlet);
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    return registration;
    }

    2.再增加处理错误页面的handler,加上@ControllerAdvice 注解

    @ControllerAdvice
    public class GlobalControllerExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "pages/404";

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
    }
    }

    针对上面这样的方法 存在一个弊端:会造成对js,css等资源的过滤,最好使用第二种方法

    2. 集成ErrorController 

    @Controller
    public class MainsiteErrorController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value=ERROR_PATH)
    public String handleError(){
    return "pages/404";
    }

    @Override
    public String getErrorPath() {
    // TODO Auto-generated method stub
    return ERROR_PATH;
    }

    }

    推荐使用第二种

  • 相关阅读:
    第一个只出现一次的字符
    把数组排成最小的数
    整数中1出现的次数
    连续子数组的最大和
    最小的K个数
    数组中出现次数超过一半的数字
    字符串的排列
    二叉搜索树与双向链表
    numpy中ravel()和flatten()
    复杂链表的复制
  • 原文地址:https://www.cnblogs.com/java-synchronized/p/8286999.html
Copyright © 2011-2022 走看看