Skip to content

Commit 598a814

Browse files
committed
完善全局异常捕获机制,以及状态码的获取
1 parent ac4c980 commit 598a814

File tree

6 files changed

+56
-30
lines changed

6 files changed

+56
-30
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
### 项目介绍
1414

1515
1. RESTful API
16-
2. Maven集成Mybatis Geneator(逆向工程)
16+
2. Maven集成Mybatis Generator(逆向工程)
1717
3. Shiro + Java-JWT实现无状态鉴权机制(Token)
1818
4. 密码加密(采用AES-128 + Base64的方式)
1919
5. 集成Redis(Jedis)
@@ -77,7 +77,7 @@ AccessToken认证,Redis的RefreshToken也可以用来判断用户是否在线
7777

7878
### 使用说明
7979

80-
#### Mybatis Geneator使用
80+
#### Mybatis Generator使用(推荐快速生成代码:[https://github.com/wang926454/SpringBootGenerator](https://github.com/wang926454/SpringBootGenerator))
8181

8282
##### 先配置src\main\resources\generator\generatorConfig.xml文件(默认配置都在原来包的下一级reverse包下),在pom.xml这一级目录(即项目根目录下)的命令行窗口执行(前提是配置了mvn)(IDEA可以直接在Maven窗口Plugins中双击执行)
8383
```

src/main/java/com/wang/controller/ExceptionController.java renamed to src/main/java/com/wang/config/ExceptionAdvice.java

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.wang.controller;
1+
package com.wang.config;
22

33
import com.wang.exception.CustomException;
44
import com.wang.exception.CustomUnauthorizedException;
@@ -13,6 +13,8 @@
1313
import org.springframework.web.bind.annotation.ExceptionHandler;
1414
import org.springframework.web.bind.annotation.ResponseStatus;
1515
import org.springframework.web.bind.annotation.RestControllerAdvice;
16+
import org.springframework.web.servlet.NoHandlerFoundException;
17+
1618
import javax.servlet.http.HttpServletRequest;
1719
import java.util.ArrayList;
1820
import java.util.HashMap;
@@ -25,7 +27,7 @@
2527
* @date 2018/8/30 14:02
2628
*/
2729
@RestControllerAdvice
28-
public class ExceptionController {
30+
public class ExceptionAdvice {
2931
/**
3032
* 捕捉所有Shiro异常
3133
* @param e
@@ -34,7 +36,7 @@ public class ExceptionController {
3436
@ResponseStatus(HttpStatus.UNAUTHORIZED)
3537
@ExceptionHandler(ShiroException.class)
3638
public ResponseBean handle401(ShiroException e) {
37-
return new ResponseBean(401, "无权访问(Unauthorized):" + e.getMessage(), null);
39+
return new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):" + e.getMessage(), null);
3840
}
3941

4042
/**
@@ -46,7 +48,7 @@ public ResponseBean handle401(ShiroException e) {
4648
@ResponseStatus(HttpStatus.UNAUTHORIZED)
4749
@ExceptionHandler(UnauthorizedException.class)
4850
public ResponseBean handle401(UnauthorizedException e) {
49-
return new ResponseBean(401, "无权访问(Unauthorized):当前Subject没有此请求所需权限(" + e.getMessage() + ")", null);
51+
return new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):当前Subject没有此请求所需权限(" + e.getMessage() + ")", null);
5052
}
5153

5254
/**
@@ -58,7 +60,7 @@ public ResponseBean handle401(UnauthorizedException e) {
5860
@ResponseStatus(HttpStatus.UNAUTHORIZED)
5961
@ExceptionHandler(UnauthenticatedException.class)
6062
public ResponseBean handle401(UnauthenticatedException e) {
61-
return new ResponseBean(401, "无权访问(Unauthorized):当前Subject是匿名Subject,请先登录(This subject is anonymous.)", null);
63+
return new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):当前Subject是匿名Subject,请先登录(This subject is anonymous.)", null);
6264
}
6365

6466
/**
@@ -68,7 +70,7 @@ public ResponseBean handle401(UnauthenticatedException e) {
6870
@ResponseStatus(HttpStatus.UNAUTHORIZED)
6971
@ExceptionHandler(CustomUnauthorizedException.class)
7072
public ResponseBean handle401(CustomUnauthorizedException e) {
71-
return new ResponseBean(401, "无权访问(Unauthorized):" + e.getMessage(), null);
73+
return new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):" + e.getMessage(), null);
7274
}
7375

7476
/**
@@ -80,7 +82,7 @@ public ResponseBean handle401(CustomUnauthorizedException e) {
8082
public ResponseBean validException(BindException e) {
8183
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
8284
Map<String, Object> result = this.getValidError(fieldErrors);
83-
return new ResponseBean(400, result.get("errorMsg").toString(), result.get("errorList"));
85+
return new ResponseBean(HttpStatus.BAD_REQUEST.value(), result.get("errorMsg").toString(), result.get("errorList"));
8486
}
8587

8688
/**
@@ -92,7 +94,7 @@ public ResponseBean validException(BindException e) {
9294
public ResponseBean validException(MethodArgumentNotValidException e) {
9395
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
9496
Map<String, Object> result = this.getValidError(fieldErrors);
95-
return new ResponseBean(400, result.get("errorMsg").toString(), result.get("errorList"));
97+
return new ResponseBean(HttpStatus.BAD_REQUEST.value(), result.get("errorMsg").toString(), result.get("errorList"));
9698
}
9799

98100
/**
@@ -102,7 +104,17 @@ public ResponseBean validException(MethodArgumentNotValidException e) {
102104
@ResponseStatus(HttpStatus.BAD_REQUEST)
103105
@ExceptionHandler(CustomException.class)
104106
public ResponseBean handle(CustomException e) {
105-
return new ResponseBean(500, e.getMessage(), null);
107+
return new ResponseBean(HttpStatus.BAD_REQUEST.value(), e.getMessage(), null);
108+
}
109+
110+
/**
111+
* 捕捉404异常
112+
* @return
113+
*/
114+
@ResponseStatus(HttpStatus.NOT_FOUND)
115+
@ExceptionHandler(NoHandlerFoundException.class)
116+
public ResponseBean handle(NoHandlerFoundException e) {
117+
return new ResponseBean(HttpStatus.NOT_FOUND.value(), e.getMessage(), null);
106118
}
107119

108120
/**
@@ -111,7 +123,7 @@ public ResponseBean handle(CustomException e) {
111123
* @param ex
112124
* @return
113125
*/
114-
@ResponseStatus(HttpStatus.BAD_REQUEST)
126+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
115127
@ExceptionHandler(Exception.class)
116128
public ResponseBean globalException(HttpServletRequest request, Throwable ex) {
117129
return new ResponseBean(this.getStatus(request).value(), ex.toString() + ": " + ex.getMessage(), null);

src/main/java/com/wang/config/shiro/jwt/JwtFilter.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,13 @@ private boolean refreshToken(ServletRequest request, ServletResponse response) {
161161
*/
162162
private void response401(ServletRequest req, ServletResponse resp, String msg) {
163163
HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
164-
httpServletResponse.setStatus(401);
164+
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
165165
httpServletResponse.setCharacterEncoding("UTF-8");
166166
httpServletResponse.setContentType("application/json; charset=utf-8");
167167
PrintWriter out = null;
168168
try {
169169
out = httpServletResponse.getWriter();
170-
String data = JsonConvertUtil.objectToJson(new ResponseBean(401, "无权访问(Unauthorized):" + msg, null));
170+
String data = JsonConvertUtil.objectToJson(new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):" + msg, null));
171171
out.append(data);
172172
} catch (IOException e) {
173173
logger.error(e.getMessage());

src/main/java/com/wang/controller/UserController.java

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@
2323
import org.springframework.beans.factory.annotation.Autowired;
2424
import org.springframework.beans.factory.annotation.Value;
2525
import org.springframework.context.annotation.PropertySource;
26+
import org.springframework.http.HttpStatus;
2627
import org.springframework.validation.annotation.Validated;
2728
import org.springframework.web.bind.annotation.*;
2829

2930
import javax.servlet.http.HttpServletResponse;
30-
import java.text.SimpleDateFormat;
3131
import java.util.*;
3232

3333
/**
@@ -63,6 +63,10 @@ public UserController(IUserService userService) {
6363
@GetMapping
6464
@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
6565
public ResponseBean user(@Validated BaseDto baseDto){
66+
if(baseDto.getPage() == null || baseDto.getRows() == null){
67+
baseDto.setPage(1);
68+
baseDto.setRows(10);
69+
}
6670
PageHelper.startPage(baseDto.getPage(), baseDto.getRows());
6771
List<UserDto> userDtos = userService.selectAll();
6872
PageInfo<UserDto> selectPage = new PageInfo<UserDto>(userDtos);
@@ -72,7 +76,7 @@ public ResponseBean user(@Validated BaseDto baseDto){
7276
Map<String, Object> result = new HashMap<String, Object>(16);
7377
result.put("count", selectPage.getTotal());
7478
result.put("data", selectPage.getList());
75-
return new ResponseBean(200, "查询成功(Query was successful)", result);
79+
return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
7680
}
7781

7882
/**
@@ -103,7 +107,7 @@ public ResponseBean online(){
103107
if(userDtos == null || userDtos.size() <= 0){
104108
throw new CustomException("查询失败(Query Failure)");
105109
}
106-
return new ResponseBean(200, "查询成功(Query was successful)", userDtos);
110+
return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", userDtos);
107111
}
108112

109113
/**
@@ -137,7 +141,7 @@ public ResponseBean login(@Validated(UserLoginValidGroup.class) @RequestBody Use
137141
String token = JwtUtil.sign(userDto.getAccount(), currentTimeMillis);
138142
httpServletResponse.setHeader("Authorization", token);
139143
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
140-
return new ResponseBean(200, "登录成功(Login Success.)", null);
144+
return new ResponseBean(HttpStatus.OK.value(), "登录成功(Login Success.)", null);
141145
} else {
142146
throw new CustomUnauthorizedException("帐号或密码错误(Account or Password Error.)");
143147
}
@@ -155,9 +159,9 @@ public ResponseBean article() {
155159
Subject subject = SecurityUtils.getSubject();
156160
// 登录了返回true
157161
if (subject.isAuthenticated()) {
158-
return new ResponseBean(200, "您已经登录了(You are already logged in)", null);
162+
return new ResponseBean(HttpStatus.OK.value(), "您已经登录了(You are already logged in)", null);
159163
} else {
160-
return new ResponseBean(200, "你是游客(You are guest)", null);
164+
return new ResponseBean(HttpStatus.OK.value(), "你是游客(You are guest)", null);
161165
}
162166
}
163167

@@ -171,7 +175,7 @@ public ResponseBean article() {
171175
@GetMapping("/article2")
172176
@RequiresAuthentication
173177
public ResponseBean requireAuth() {
174-
return new ResponseBean(200, "您已经登录了(You are already logged in)", null);
178+
return new ResponseBean(HttpStatus.OK.value(), "您已经登录了(You are already logged in)", null);
175179
}
176180

177181
/**
@@ -188,7 +192,7 @@ public ResponseBean findById(@PathVariable("id") Integer id){
188192
if(userDto == null){
189193
throw new CustomException("查询失败(Query Failure)");
190194
}
191-
return new ResponseBean(200, "查询成功(Query was successful)", userDto);
195+
return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", userDto);
192196
}
193197

194198
/**
@@ -219,7 +223,7 @@ public ResponseBean add(@Validated(UserEditValidGroup.class) @RequestBody UserDt
219223
if(count <= 0){
220224
throw new CustomException("新增失败(Insert Failure)");
221225
}
222-
return new ResponseBean(200, "新增成功(Insert Success)", userDto);
226+
return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", userDto);
223227
}
224228

225229
/**
@@ -254,7 +258,7 @@ public ResponseBean update(@Validated(UserEditValidGroup.class) @RequestBody Use
254258
if(count <= 0){
255259
throw new CustomException("更新失败(Update Failure)");
256260
}
257-
return new ResponseBean(200, "更新成功(Update Success)", userDto);
261+
return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", userDto);
258262
}
259263

260264
/**
@@ -271,7 +275,7 @@ public ResponseBean delete(@PathVariable("id") Integer id){
271275
if(count <= 0){
272276
throw new CustomException("删除失败,ID不存在(Deletion Failed. ID does not exist.)");
273277
}
274-
return new ResponseBean(200, "删除成功(Delete Success)", null);
278+
return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
275279
}
276280

277281
/**
@@ -287,7 +291,7 @@ public ResponseBean deleteOnline(@PathVariable("id") Integer id){
287291
UserDto userDto = userService.selectByPrimaryKey(id);
288292
if(JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount())){
289293
if(JedisUtil.delKey(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount()) > 0){
290-
return new ResponseBean(200, "剔除成功(Delete Success)", null);
294+
return new ResponseBean(HttpStatus.OK.value(), "剔除成功(Delete Success)", null);
291295
}
292296
}
293297
throw new CustomException("剔除失败,Account不存在(Deletion Failed. Account does not exist.)");

src/main/java/com/wang/model/common/BaseDto.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,11 @@ public class BaseDto implements Serializable {
1717

1818
/** 当前页数 */
1919
@Transient
20-
@NotNull(message = "当前页数不能为空")
2120
@Min(value = 1, message = "当前页数不能小于1")
2221
private Integer page;
2322

2423
/** 每页条数 */
2524
@Transient
26-
@NotNull(message = "每页条数不能为空")
2725
@Min(value = 1, message = "每页条数不能小于1")
2826
@Max(value = 50, message = "每页条数不能大于50")
2927
private Integer rows;

src/main/resources/application.yml

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ spring:
77
url: jdbc:mysql://127.0.0.1:3306/shirojwt?useSSL=false&useUnicode=true&characterEncoding=UTF-8
88
username: root
99
password: root
10-
# 使用druid数据源
10+
# 使用Druid数据源
1111
type: com.alibaba.druid.pool.DruidDataSource
1212
driver-class-name: com.mysql.jdbc.Driver
1313
filters: stat
@@ -23,19 +23,31 @@ spring:
2323
testOnReturn: false
2424
poolPreparedStatements: true
2525
maxOpenPreparedStatements: 20
26+
# 404交给异常处理器处理
27+
mvc:
28+
throw-exception-if-no-handler-found: true
29+
# 404交给异常处理器处理
30+
resources:
31+
add-mappings: false
2632

2733
mybatis:
34+
# Mybatis配置Mapper路径
2835
mapper-locations: classpath:mapper/*.xml
36+
# Mybatis配置Model类对应
2937
type-aliases-package: com.wang.model.entity
3038

3139
pagehelper:
3240
params: count=countSql
41+
# 指定分页插件使用哪种方言
3342
helper-dialect: mysql
43+
# 分页合理化参数 pageNum<=0时会查询第一页 pageNum>pages(超过总数时) 会查询最后一页
3444
reasonable: 'true'
3545
support-methods-arguments: 'true'
3646

3747
mapper:
48+
# 通用Mapper的insertSelective和updateByPrimaryKeySelective中是否判断字符串类型!=''
3849
not-empty: true
3950

4051
logging:
41-
level.com.wang.mapper: debug
52+
# Debug打印SQL
53+
level.com.wang.mapper: debug

0 commit comments

Comments
 (0)