SpringBoot配置系統全局異常映射處理
這里的異常分類從系統處理異常的角度看,主要分類兩類:業務異常和系統異常。
1、業務異常業務異常主要是一些可預見性異常,處理業務異常,用來提示用戶的操作,提高系統的可操作性。
常見的業務異常提示:1)請輸入xxx2)xxx不能為空3)xxx重復,請更換
2、系統異常系統異常主要是一些不可預見性異常,處理系統異常,可以讓展示出一個友好的用戶界面,不易給用戶造成反感。如果是一個金融類系統,在用戶界面出現一個系統異常的崩潰界面,很有可能直接導致用戶流失。
常見的系統異常提示:1)頁面丟失4042)服務器異常500
二、解決應用啟動后404界面<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>2、自定義首頁接口
import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class IndexController { @RequestMapping('/') public String index(ModelMap modelMap) {modelMap.addAttribute('name','知了一笑') ;return 'index'; }}3、首頁界面
<!DOCTYPE html><html><head lang='en'> <meta charset='UTF-8' /> <title></title></head><body><h1 th:text='${name}'></h1></body></html>4、運行效果
public class ServiceException extends Exception { public ServiceException (String msg){super(msg); }}3、自定義異常描述對象
public class ReturnException { // 響應碼 private Integer code; // 異常描述 private String msg; // 請求的Url private String url; // 省略 get set 方法}4、統一異常處理格式
1)兩個基礎注解@ControllerAdvice 定義統一的異常處理類@ExceptionHandler 定義異常類型對應的處理方式2)代碼實現
import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;@ControllerAdvice// 異常以Json格式返回 等同 ExceptionHandler + ResponseBody 注解// @RestControllerAdvicepublic class HandlerException { /** * 自定義業務異常映射,返回JSON格式提示 */ @ExceptionHandler(value = ServiceException.class) @ResponseBody public ReturnException handler01 (HttpServletRequest request,ServiceException e){ReturnException returnException = new ReturnException() ;returnException.setCode(600);returnException.setMsg(e.getMessage());returnException.setUrl(String.valueOf(request.getRequestURL()));return returnException ; } /** * 服務異常 */ @ExceptionHandler(value = Exception.class) public ModelAndView handler02 (HttpServletRequest request,Exception e){ModelAndView modelAndView = new ModelAndView() ;modelAndView.addObject('ExeMsg', e.getMessage());modelAndView.addObject('ReqUrl', request.getRequestURL());modelAndView.setViewName('/exemsg');return modelAndView ; }}5、簡單的測試接口
@Controllerpublic class ExeController { /** * { * 'code': 600, * 'msg': '業務異常:ID 不能為空', * 'url': 'http://localhost:8003/exception01' * } */ @RequestMapping('/exception01') public String exception01 () throws ServiceException {throw new ServiceException('業務異常:ID 不能為空'); } @RequestMapping('/exception02') public String exception02 () throws Exception {throw new Exception('出現異常,全體臥倒'); }}
GitHub:知了一笑https://github.com/cicadasmile/spring-boot-base
以上就是SpringBoot配置系統全局異常映射處理的詳細內容,更多關于SpringBoot 異常映射處理的資料請關注好吧啦網其它相關文章!
相關文章:
