需求:
在service层处理业务的时候,总归会有一些校验异常的情况,此时,我们可以在service主动抛出对应的异常(XxxException extends RuntimeException),然后在controller层进行捕捉,进行相应的处理,再返回。
弊端:
这将导致,在controller每次调用service方法时,都要进行一次捕捉,以及捕捉后的处理,导致大量重复的代码。
处理方式:
通过动态代理,在controller生成service的代理类,再代理中进行try catch,和处理异常。
下面直接上代码:
校验使用的工具类
public class CheckUtil {
public static void checkMobile(String mobile) {
if(!Pattern.matches("^1[3456789]\d{9}$", mobile)) {
throw new XxxException(XxxExceptionEnum.MOBILE_ERROR);
}
}
}
service层
public interface MemberService {
Result login(String mobile, String password);
}