spring boot 默認狀況下會映射到 /error 進行異常處理,提示不友好,須要自定義異常處理,提供友好展現java
1.自定義異常類(spring 對於 RuntimeException 異常纔會進行事務回滾):web
1 package com.zpark.tools.exception; 3 /** 4 * @author cosmo 5 * @Title: CommonException 6 * @ProjectName 7 * @Description: 8 * @date 9 */ 10 public class CommonException extends RuntimeException{ 11 12 private String rerutnCode; 13 14 private String errorMsg; 15 16 public CommonException(String returnCode ,String errorMsg){ 17 this.returnCode = returnCode; 18 this.errorMsg = errorMsg; 19 } 20 21 public String getReturnCode() { 22 return returnCode; 23 } 24 25 public void setReturnCode(String returnCode) { 26 this.returnCode = returnCode; 27 } 28 29 public String getErrorMsg() { 30 return errorMsg; 31 } 32 33 public void setErrorMsg(String errorMsg) { 34 this.errorMsg = errorMsg; 35 } 36 }
2.定義全局異常類:spring
1 package com.zpark.tools.exception; 2 3 import com.zpark.tools.Constants; 4 import org.slf4j.Logger; 5 import org.slf4j.LoggerFactory; 6 import org.springframework.web.bind.annotation.ControllerAdvice; 7 import org.springframework.web.bind.annotation.ExceptionHandler; 8 import org.springframework.web.bind.annotation.ResponseBody; 10 import javax.servlet.http.HttpServletRequest; 11 import java.util.HashMap; 12 import java.util.Map; 13 14 /** 15 * @author cosmo 16 * @Title: CommonExceptionHandler 17 * @ProjectName 18 * @Description: 19 * @date 20 */ 21 @ControllerAdvice 22 public class CommonExceptionAdvice { 23 24 private Logger log = LoggerFactory.getLogger(CommonExceptionAdvice.class); 25 /** 26 * 全局異常捕捉處理 27 * @param ex 28 * @return 29 */ 30 @ResponseBody 31 @ExceptionHandler(value = Exception.class) 32 public Map errorHandler(HttpServletRequest request,Exception ex) {34 Map map = new HashMap(); 35 map.put("retrnCode", 100); 36 map.put("errorMsg", ex.getMessage());51 return map; 52 }67 }
運行中出現異常,會返回報錯信息和錯誤codethis