社区网站项目3.9 统一处理异常

    技术2022-07-11  86

      @ControllerAdvice (1)用于修饰类,表示该类是Controller的全局配置类。 (2)在此类中,可以对Controller进行如下三种全局配置: 异常处理方案、绑定数据方案、绑定参数方案。   @ExceptionHandler (1)用于修饰方法,该方法会在Controller出现异常后被调用,用于处理捕获到的异常。   @ModelAttribute (1)用于修饰方法,该方法会在Controller方法执行前被调用,用于为Model对象绑定参数。   @DataBinder (1)用于修饰方法,该方法会在Controller方法执行前被调用,用于绑定参数的转换器。   把404.html,500.html放进resources->templates->error下面。   在MessageController类里的getLetterList方法里加一句Integer.valueOf(“abc”)人为制造一个错误。   在HomeController类里,添加

    @RequestMapping(path="/error",method=RequestMethod.GET) public String getErrorPage(){ return "/error/500"; } // 拒绝访问时的提示页面(或者说没有权限时) @RequestMapping(path = "/denied", method = RequestMethod.GET) public String getDeniedPage(){ return "/error/404"; }

      在controller包下新建advice包下新建ExceptionAdvice类,在里面加@ControllerAdvice(annotations=Controller.class)注解,

    @ExceptionHandler({Exception.class}) public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.error("服务器发生异常:"+e.getMessage()); for(StackTraceElement element:e.getStackTrace()){ //遍历这个异常栈 数组 logger.error(element.toString()); // 记录日志 } //有时候浏览器不是想要你返回html,而是数据文本信息(比如异步请求) String xRequestedWith = request.getHeader("x-requested-with"); //一个小技巧 if("XMLHttpRequest".equals(xRequestedWith)){ //说明这是异步请求 response.setContentType("application/plain;charset=utf-8"); //给浏览器返回数据 PrintWriter writer = response.getWriter(); writer.write(CommunityUtil.getJSONString(1,"服务器异常!")); }else{ response.sendRedirect(request.getContextPath()+"/error"); //简单地返回html } }

      在MessageController类里的sendLetter方法里加上Integer.valueOf(“abc”); //造一个异步请求错误,那么访问sendLetter方法的时候,会返回500错误页面。   当访问一个不存在的路径的时候,则返回404错误页面。

    Processed: 0.011, SQL: 9