该笔记是看视频的记录,视频地址:http://www.imooc.com/learn/810
一、使用@Valid做表单验证
![](https://img.haomeiwen.com/i8179604/10a28db340031ed2.png)
![](https://img.haomeiwen.com/i8179604/87936c0e4e86efc2.png)
二、使用AOP处理请求
![](https://img.haomeiwen.com/i8179604/21ec1fdedf3f895a.png)
![](https://img.haomeiwen.com/i8179604/6c6807d12f06c447.png)
![](https://img.haomeiwen.com/i8179604/7a7c34a71f4fb6c9.png)
![](https://img.haomeiwen.com/i8179604/2fd347c856b4d4b3.png)
三、统一异常处理
1、异常情况处理
![](https://img.haomeiwen.com/i8179604/56b3212d219da6a3.png)
![](https://img.haomeiwen.com/i8179604/950613c9a937946a.png)
![](https://img.haomeiwen.com/i8179604/2ebde3f7ad11a779.png)
2、更好的处理方式
上面的返回结果并不友好,不方便前端处理,我们期望的是下图这样的:包括一个code表示成功失败,msg表示处理结果信息,data表示对象信息
![](https://img.haomeiwen.com/i8179604/43f89d58bd379f6d.png)
下面来看实现:
![](https://img.haomeiwen.com/i8179604/7e8d834d5c532ed2.png)
![](https://img.haomeiwen.com/i8179604/fe6eb4e400fb63f6.png)
![](https://img.haomeiwen.com/i8179604/37b2d2e861379f01.png)
3、Exception的处理
当系统发生异常时
![](https://img.haomeiwen.com/i8179604/69a845694b3a585f.png)
前台就会收到这样的消息
![](https://img.haomeiwen.com/i8179604/f0b80b78bac4ff18.png)
这不是我们想要的,我们希望发生异常的时候依然可以正常返回,可以通过一个ExceptionHandle来实现
![](https://img.haomeiwen.com/i8179604/04a964897663e111.png)
就得到了我们想要的返回格式
![](https://img.haomeiwen.com/i8179604/6372ecc50f1922eb.png)
4、异常精细化处理:为异常编号
![](https://img.haomeiwen.com/i8179604/9fdd8d533ff648f6.png)
![](https://img.haomeiwen.com/i8179604/df5768ebba7eb1ec.png)
![](https://img.haomeiwen.com/i8179604/8ce0dd2fa98a8aec.png)
5、异常编号用枚举类型代替
100、101这种编号写在具体业务逻辑里面显然不妥,时间长了,前台抛出一个100的异常,我们很难再想起这个100到底代表什么,也不好找到这些代码,通常的做法是把所有异常编号都放在一个枚举类型中,这样就好查啦
如下图,我们新建了一个枚举类,有了这个枚举类,我们再增加异常类型、修改异常提示,就再也不用去茫茫code海里面去搜索了。
![](https://img.haomeiwen.com/i8179604/ed9049c08bcb7869.png)
![](https://img.haomeiwen.com/i8179604/d6ef1bfef99f9e9b.png)
![](https://img.haomeiwen.com/i8179604/aaaaee5ca124066e.png)
![](https://img.haomeiwen.com/i8179604/1487b5e7b6e403a0.png)
四、单元测试
1、测试Service
![](https://img.haomeiwen.com/i8179604/79b843d8758fc0b4.png)
![](https://img.haomeiwen.com/i8179604/5a5050ed8975fbce.png)
2、测试API
![](https://img.haomeiwen.com/i8179604/6003811809191553.png)
![](https://img.haomeiwen.com/i8179604/f676cce5aa7b3722.png)
![](https://img.haomeiwen.com/i8179604/e19731ef763e6012.png)
maven打包的时候也会自动运行这些单元测试,执行mvn clean package
![](https://img.haomeiwen.com/i8179604/85dfea1183285be1.png)
网友评论