spring boot 默认情况下会映射到 /error 进行异常处理,提示不友好,需要自定义异常处理,提供友好展示
1.自定义异常类(spring 对于 RuntimeException 异常才会进行事务回滚):
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.定义全局异常类:
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 }
运行中出现异常,会返回报错信息和错误code
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/18577.html