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开发的时候推荐使用第二种。