以前写过一篇博客(http://www.javashuo.com/article/p-onrrgbca-ch.html),使用@ControllerAdvice对代码中的全局异常作处理。可是这种方式过于繁琐,而且会影响可读性,抛出业务异常的示例:express
Route route = routeTravelAppService.getRouteInfo(routeId); if(route == null ){ throw new BaseException(BaseException.TICKET_NOTE_TYPE_IS_NOT_AVAILABLE,"行程为空"); } |
若使用Assert工具类上面的代码能够简化为:工具
Assert.hasText((name, "参数错误!"); |
这样能够大大加强代码的可读性,下面咱们来介绍一下Assert类中的经常使用断言方法。spa
下面列举几个经常使用方法.net
方法 | 说明 |
isTrue(boolean expression, String message) | 当 expression 不为 true 抛出异常 |
isNull(Object object, String message) | 当 object 不为 null 时抛出异常 |
notNull(Object object, String message) | 当 object 为 null 时抛出异常 |
hasLength(String text, String message) | 当 text为 空字符串 时抛出异常 |
hasText(String text, String message) | text 不能为 null 且必须至少包含一个非空格的字符,不然抛出异常 |
示例:blog
Assert.hasText(strategy_id, "strategy_id can not be NULL"); |