springboot 常用的異常處理方式
阿新 • • 發佈:2019-02-12
tps 重載方法 entity 實現 頁面 erro mapping 發的 exce
springboot常用的異常處理推薦:
一.創建一個異常控制器,並實現ErrorController接口:
package com.example.demo.controller; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class BaseErrorController implements ErrorController { @Override public String getErrorPath() { return "/error/error"; } @RequestMapping("/error") public String getError() { return getErrorPath(); } }
當系統內發生錯誤後會跳轉到error頁面。
二.創建一個異常句柄ErrorExceperHandler
package com.example.demo.handler; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class ErrorExceperHandler { @ExceptionHandler @ResponseStatus(HttpStatus.OK) public ModelAndView processException(Exception exception) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", exception.getMessage()); modelAndView.setViewName("/error/error"); return modelAndView; } @ExceptionHandler @ResponseStatus(HttpStatus.OK) public ModelAndView processException(RuntimeException exception) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", exception.getMessage()); modelAndView.setViewName("/error/error"); return modelAndView; } }
重載方法針對Exception和RuntimeException進行攔截,當系統發生異常後,會跳轉到異常頁面。
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.example.demo.entity.Student; @Controller @RequestMapping("/student/") public class StudentController { @RequestMapping("show") public String show(Model model) throws Exception { Student stu = new Student(); stu.setId(1001); stu.setName("小明"); model.addAttribute("student", stu); if (!"a".equals("")) { throw new RuntimeException("RuntimeException...."); } if (!"a".equals("")) { throw new Exception("Exception...."); } return "show"; } }
在做spring或springboot開發的時候推薦使用第二種。
springboot 常用的異常處理方式