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