1、去掉try-catch
1.1、異常處理規範
不要在業務代碼中進行捕獲異常, 即 dao、service、controller 層的所以異常都全部拋出到上層. 這樣不會導致業務代碼中的一堆 try-catch
會混亂業務代碼
1.2、定義全局異常處理器
import com.asiainfo.group.tmallcore.util.WebResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author xulong3
* @Title: file_name
* @Package package_name
* @Description: todo
* @date 2020/6/8 17:50
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public WebResult<String> exceptionHandler(Exception e) {
WebResult<String> wr = new WebResult<>();
wr.setCode(500);
wr.setMessage("全局異常處理器捕獲到了Exception");
return wr;
}
}
1.3、controller層拋出異常
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xulong3
* @Title: file_name
* @Package package_name
* @Description: todo
* @date 2020/6/8 17:55
*/
@RestController
@RequestMapping("/exception")
public class ExceptionController {
@RequestMapping(method = RequestMethod.GET)
public void exception() throws Exception{
throw new Exception();
}
}
2、去掉if-else
採用Assert類斷言,很多框架、工具包都提供了Assert類,例如spring提供的org.springframework.util.Assert