第10章 异常处理

2019-01-22  本文已影响0人  yangsg

常规B/S结构网站的异常处理主要有两种方式

SpringBoot中关于两种方式异常处理都给予了一定的支持

根据HTTP协议码处理异常

SpringBoot中没有web.xml文件,故需要一些其他方法完成相应操作。
新建错误页面

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, 
          Object handler,ModelAndView modelAndView) throws Exception {
      if(response.getStatus()==500){
            modelAndView.setViewName("/500.html");
      }else if(response.getStatus()==404){
            modelAndView.setViewName("/404.html");
      }
}

注册拦截器时,拦截范围设置为: /**
2.自定义Controller,实现ErrorController接口
SpringBoot默认通过/error处理异常,编写类重写ErrorController接口并重写相关逻辑即可实现相关效果

MyErrorHandler.java

@Controller
public class MyErrorHandler implements ErrorController{
    
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 404){
            return "redirect:/404.html";
        }else if(statusCode == 500){
            return "redirect:/500.html";
        }else{
            return "redirect:/error.html";
        }
    }

    @Override
    public String getErrorPath() {
        return "redirect:/error";
    }
}

根据异常类型处理异常

新建com.neuedu.exception包,新建类GlobalDefaultExceptionHandler。
同时使用@ControllerAdvice注册该类

GlobalDefaultExceptionHandler.java

package com.neuedu.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

     @ExceptionHandler(value = Exception.class)
     public ModelAndView defaultErrorHandler(HttpServletRequest req,Exception e) {
         System.out.println("全局异常执行");  
         ModelAndView mv = new ModelAndView();
         mv.addObject("exception", e);
         mv.addObject("url", req.getRequestURL());
         mv.setViewName("/error.html");
         return mv;      
     }
}

其中,方法上方的@ExceptionHandler注解表示处理的异常类型,本文中选择Exception,即可以表示处理所有异常

@ExceptionHandler(value = Exception.class)

此段代码表示当发生异常时记录异常信息和发生异常的url,将相关信息发送给模板error.html。在模板中显示相关内容

error.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <div th:text="${url}"></div>
  <div th:text="${exception.message}"></div>
</body>
</html>

任意编写测试数据

@RequestMapping("/testError")
public String testError() throws Exception{
    System.out.println(5/0);
    return us.getUUID();
}

测试,访问链接: http://localhost:8080/myproj1/testError
测试结果

测试结果
上一篇 下一篇

猜你喜欢

热点阅读