Browse Source

处理了错误码

wuweihao 5 years ago
parent
commit
3cef7f3c3c

+ 30 - 19
xiaoan-common/src/main/java/com/xiaoan/common/constant/MsgCode.java

@@ -6,34 +6,45 @@ package com.xiaoan.common.constant;
 public class MsgCode {
 
     public static final int SUCCESS_CODE = 2000;
-    public static final String SUCCESS_MSG = "success";
-
+    public static final String msg_SUCCESS = "success";
+    
     public static final int ERROR_CODE = 5000;
     public static final String ERROR_MSG = "error";
 
-    public static final int FAILURE_CODE_3001 = 3001;
-    public static final String FAILURE_MSG_3001 = "缺少必要参数";
 
-    public static final int FAILURE_CODE_3002 = 3002;
-    public static final String FAILURE_MSG_3002 = "id不存在";
+    // 30xx 公共模块
+    public static final int e_COMMON_3001 = 3001;
+    public static final String msg_COMMON_3001 = "缺少必要参数";
+
+    public static final int e_COMMON_3002 = 3002;
+    public static final String msg_COMMON_3002 = "id不存在";
+
+    //40xx是用户管理模块的
+    public static final int e_ADMIN_4001 = 4001;
+    public static final String msg_ADMIN_4001 = "用户不存在";
+
+    public static final int e_ADMIN_4002 = 4002;
+    public static final String msg_ADMIN_4002 = "密码不正常";
+
+    public static final int e_ADMIN_4003 = 4003;
+    public static final String msg_ADMIN_4003 = "该账户已停用,请跟管理员联系";
 
-    //400x是用户模块的
-    public static final int FAILURE_CODE_4001 = 4001;
-    public static final String FAILURE_MSG_4001 = "用户不存在";
+    //41XX 角色模块
+    public static final int e_ADMIN_4100 = 4100;
+    public static final String msg_ADMIN_4100 = "角色不存在";
 
-    public static final int FAILURE_CODE_4002 = 4002;
-    public static final String FAILURE_MSG_4002 = "密码不正常";
+    //42XX 资源模块
+    public static final int e_ADMIN_4200 = 4200;
+    public static final String msg_ADMIN_4200 = "资源不存在";
 
-    public static final int FAILURE_CODE_4003 = 4003;
-    public static final String FAILURE_MSG_4003 = "该账户已停用,请跟管理员联系";
+    //43XX 部门模块
+    public static final int e_ADMIN_4300 = 4300;
+    public static final String msg_ADMIN_4300 = "部门名称已存在";
 
-    //500x是部门模块的
-    public static final int FAILURE_CODE_5001 = 5001;
-    public static final String FAILURE_MSG_5001 = "部门名称已存在";
+    //4500 shiro权限
+    public static final int e_SHIRO_4500 = 4500;
+    public static final String msg_SHIRO_4500  = "没有授权";
 
-    //500x是部门模块的
-    public static final int FAILURE_CODE_6001 = 6001;
-    public static final String FAILURE_MSG_6001 = "角色不存在";
 
 
 

+ 35 - 0
xiaoan-common/src/main/java/com/xiaoan/common/exception/BaseRuntimeException.java

@@ -0,0 +1,35 @@
+package com.xiaoan.common.exception;
+
+public class BaseRuntimeException extends RuntimeException{
+
+    private static final long serialVersionUID = -1518945670203783450L;
+    private Integer code;
+    private String msg;
+
+    public BaseRuntimeException(String msg){
+        super(msg);
+        this.msg = msg;
+    }
+
+    public BaseRuntimeException(Integer code, String msg){
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public void setCode(Integer code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+}

+ 34 - 0
xiaoan-common/src/main/java/com/xiaoan/common/exception/JwtAuthenticationException.java

@@ -0,0 +1,34 @@
+package com.xiaoan.common.exception;
+
+import org.apache.shiro.ShiroException;
+
+public class JwtAuthenticationException extends ShiroException {
+
+    private static final long serialVersionUID = 2899335020273674736L;
+
+    private int code;
+
+    private String msg;
+
+    public JwtAuthenticationException(int code, String msg){
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public void setCode(int code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+}

+ 1 - 0
xiaoan-web/src/main/java/com/xiaoan/web/aop/WebControllerLog.java

@@ -10,4 +10,5 @@ import java.lang.annotation.*;
 @Documented
 public @interface WebControllerLog {
     String description() default "";
+
 }

+ 22 - 2
xiaoan-web/src/main/java/com/xiaoan/web/backend/BaseController.java

@@ -1,5 +1,7 @@
 package com.xiaoan.web.backend;
 
+import com.xiaoan.domain.backend.LogEntity;
+import com.xiaoan.service.backend.LogService;
 import com.xiaoan.web.shiro.JWTUtil;
 import com.xiaoan.web.shiro.JwtUtil2;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -14,13 +16,31 @@ public class BaseController {
     @Autowired
     protected HttpServletRequest request;
 
-    protected String getTokenUserName(){
+    @Autowired
+    private LogService logService;
+
+    String getTokenUserName(){
         String token = request.getHeader("Authorization");
 //        return JWTUtil.getUsername(token);
         return JwtUtil2.getUsername(token);
     }
 
-    protected String getToken(){
+    String getToken(){
         return request.getHeader("Authorization");
     }
+
+
+    /**
+     * 自定义日志方法
+     *
+     * 场景名称是动态,需要自定义方法
+     */
+    void saveLog(String type, String desc){
+        LogEntity logEntity = new LogEntity();
+        logEntity.setUserId(JwtUtil2.getUserId(getToken()));
+        logEntity.setType(type);
+        logEntity.setDescription(desc);
+
+        logService.save(logEntity);
+    }
 }

+ 6 - 6
xiaoan-web/src/main/java/com/xiaoan/web/backend/DepartmentController.java

@@ -57,7 +57,7 @@ public class DepartmentController extends BaseController {
     @PostMapping("save")
     public ResultJson save(@RequestBody DepartmentRequest param){
         if(StringUtils.isEmpty(param.getName()) || StringUtils.isEmpty(param.getNum())){
-            return new ResultJson(MsgCode.FAILURE_CODE_3001, MsgCode.FAILURE_MSG_3001);
+            return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
         }
 
         Long id = param.getId();
@@ -66,7 +66,7 @@ public class DepartmentController extends BaseController {
         if (id == null) {
             entity = departmentService.findByName(param.getName());
             if(entity != null){
-                return new ResultJson(MsgCode.FAILURE_CODE_5001, MsgCode.FAILURE_MSG_5001);
+                return new ResultJson(MsgCode.ERROR_CODE, MsgCode.ERROR_MSG);
             }
 
             entity = new DepartmentEntity();
@@ -75,7 +75,7 @@ public class DepartmentController extends BaseController {
         } else {
             entity = departmentService.findById(id);
             if (entity == null) {
-                return new ResultJson(MsgCode.FAILURE_CODE_3002, MsgCode.FAILURE_MSG_3002);
+                return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
             }
             BeanUtils.copyProperties(param, entity);
             entity.setUpdateTime(new Date());
@@ -84,7 +84,7 @@ public class DepartmentController extends BaseController {
         }
 
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @RequiresPermissions("admin:department:remove")
@@ -94,7 +94,7 @@ public class DepartmentController extends BaseController {
     @GetMapping("delete/all/{id}")
     public ResultJson deleteAll(@PathVariable String id){
         departmentService.deleteByIds(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @RequiresPermissions("admin:department:remove")
@@ -103,7 +103,7 @@ public class DepartmentController extends BaseController {
     @PostMapping("delete/{id}")
     public ResultJson delete(@PathVariable Long id){
         departmentService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @WebControllerLog(description = "部门信息-获取部门")

+ 45 - 5
xiaoan-web/src/main/java/com/xiaoan/web/backend/ExceptionController.java

@@ -1,10 +1,15 @@
 package com.xiaoan.web.backend;
 
+import com.xiaoan.common.constant.MsgCode;
+import com.xiaoan.common.exception.BaseRuntimeException;
 import com.xiaoan.common.util.ResultJson;
+import lombok.extern.log4j.Log4j2;
 import org.apache.shiro.ShiroException;
+import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.authz.UnauthorizedException;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.ResponseStatus;
 import org.springframework.web.bind.annotation.RestControllerAdvice;
 
@@ -14,21 +19,49 @@ import javax.servlet.http.HttpServletRequest;
  * 统一捕捉异常,自定义返回参数
  * 这里只可以捕获controller层的异常。
  */
-//@RestControllerAdvice
+@Log4j2
+@RestControllerAdvice
 public class ExceptionController {
 
     // 捕捉shiro的异常
     @ResponseStatus(HttpStatus.UNAUTHORIZED)
     @ExceptionHandler(ShiroException.class)
     public ResultJson handle401(ShiroException e) {
-        return new ResultJson(40002, e.getMessage());
+        return new ResultJson(5003, e.getMessage());
     }
 
-    // 捕捉UnauthorizedException
+//    @ResponseStatus(HttpStatus.UNAUTHORIZED)
+
+//    @ResponseBody
+//    @ResponseStatus(HttpStatus.OK)
+//    @ExceptionHandler(AuthenticationException.class)
+//    public ResultJson handle401(AuthenticationException e) {
+//        return new ResultJson(500001, e.getMessage());
+//    }
+
+
+//    @ResponseBody
+//    @ResponseStatus(HttpStatus.OK)
+//    @ExceptionHandler(AuthenticationException.class)
+//    public ResultJson handle401(AuthenticationException e) {
+//        Throwable throwable = e.getCause();
+//        if (throwable instanceof AuthenticationException) {
+//
+//            return new ResultJson(500001, throwable.getMessage());
+//        }
+//        return new ResultJson(400001, e.getMessage());
+//    }
+
+
+    /**
+     * 捕捉UnauthorizedException
+     *
+     * 权限不够,会抛这个异常
+     */
     @ResponseStatus(HttpStatus.UNAUTHORIZED)
     @ExceptionHandler(UnauthorizedException.class)
     public ResultJson handle401() {
-        return new ResultJson(40003, "Unauthorized");
+        return new ResultJson(MsgCode.e_SHIRO_4500, MsgCode.msg_SHIRO_4500);
     }
 
     // 捕捉其他所有异常
@@ -47,7 +80,14 @@ public class ExceptionController {
         return HttpStatus.valueOf(statusCode);
     }
 
-
+    @ResponseBody
+    @ExceptionHandler(BaseRuntimeException.class)
+    @ResponseStatus(HttpStatus.OK)
+    public ResultJson runtimeExceptionHandler(HttpServletRequest request, BaseRuntimeException e) {
+        log.error(request.getRequestURI() + ":" + e.getMsg());
+//        return Result.failure(e.getCode() == null ? Result.CODE_FAILURE : e.getCode(), e.getMsg());
+        return new ResultJson(e.getCode(), e.getMsg());
+    }
 
 
 }

+ 4 - 4
xiaoan-web/src/main/java/com/xiaoan/web/backend/IndexController.java

@@ -58,18 +58,18 @@ public class IndexController {
         // 1.获取用户
         UserEntity userEntity = userService.findByUserName(param.getUserName());
         if (userEntity == null){
-            return new ResultJson(MsgCode.FAILURE_CODE_4001, MsgCode.FAILURE_MSG_4001);
+            return new ResultJson(MsgCode.e_ADMIN_4001, MsgCode.msg_ADMIN_4001);
         }
 
         // 验证密码
         String decryptName = PasswordUtils.decrypt(userEntity.getPassword(), param.getPassword(), PasswordUtils.getStaticSalt());
         if (!param.getUserName().equals(decryptName)) {
-            return new ResultJson(MsgCode.FAILURE_CODE_4002, MsgCode.FAILURE_MSG_4002);
+            return new ResultJson(MsgCode.e_ADMIN_4002, MsgCode.msg_ADMIN_4002);
         }
 
         // 检查账号是否启用
         if (userEntity.getStatus() != 0) {
-            return new ResultJson(MsgCode.FAILURE_CODE_4003, MsgCode.FAILURE_MSG_4003);
+            return new ResultJson(MsgCode.e_ADMIN_4003, MsgCode.msg_ADMIN_4003);
         }
 
         // 获取用户菜单
@@ -127,7 +127,7 @@ public class IndexController {
             redisTemplate.delete(username);
         }
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 }

+ 5 - 5
xiaoan-web/src/main/java/com/xiaoan/web/backend/IssueController.java

@@ -76,7 +76,7 @@ public class IssueController extends BaseController {
         Long userId = JwtUtil2.getUserId(getToken());
         issueEntity.setUserId(userId);
         issueService.save(issueEntity);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     /**
@@ -90,7 +90,7 @@ public class IssueController extends BaseController {
 
         IssueEntity entity = issueService.findById(id);
         if (entity == null) {
-            return new ResultJson(MsgCode.FAILURE_CODE_3001, MsgCode.FAILURE_MSG_3001);
+            return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
         }
 
         entity.setReply(item);
@@ -98,7 +98,7 @@ public class IssueController extends BaseController {
 
         issueService.update(entity);
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     /**
@@ -110,7 +110,7 @@ public class IssueController extends BaseController {
     @GetMapping("delete/{id}")
     public ResultJson save(@PathVariable Long id){
         issueService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @WebControllerLog(description = "问题反馈-删除问题")
@@ -119,7 +119,7 @@ public class IssueController extends BaseController {
     @GetMapping("delete/all/{id}")
     public ResultJson deleteAll(@PathVariable String id){
         issueService.deleteByIds(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 

+ 24 - 5
xiaoan-web/src/main/java/com/xiaoan/web/backend/PersonalCenterController.java

@@ -5,10 +5,12 @@ import com.xiaoan.common.constant.MsgCode;
 import com.xiaoan.common.model.PageDto;
 import com.xiaoan.common.util.ResultJson;
 import com.xiaoan.domain.backend.CameraEntity;
+import com.xiaoan.domain.backend.LogEntity;
 import com.xiaoan.domain.backend.SceneProEntity;
 import com.xiaoan.domain.dto.request.SceneProRequest;
 import com.xiaoan.domain.dto.response.SceneResponse;
 import com.xiaoan.service.backend.CameraService;
+import com.xiaoan.service.backend.LogService;
 import com.xiaoan.service.backend.SceneService;
 import com.xiaoan.service.backend.UserService;
 import com.xiaoan.web.aop.WebControllerLog;
@@ -40,6 +42,9 @@ public class PersonalCenterController extends BaseController {
     @Autowired
     private CameraService cameraService;
 
+    @Autowired
+    private LogService logService;
+
     @RequiresPermissions("admin:scene:list")
     @WebControllerLog(description = "个人中心-我的场景/搜索")
     @ApiOperation("获取场景列表/搜索")
@@ -61,12 +66,17 @@ public class PersonalCenterController extends BaseController {
     }
 
     @RequiresPermissions("admin:scene:remove")
-    @WebControllerLog(description = "个人中心-我的场景/删除")
+//    @WebControllerLog(description = "个人中心-我的场景/删除")
     @ApiOperation("删除场景")
     @GetMapping("scene/delete/{id}")
     public ResultJson delete(@PathVariable Long id){
+        SceneProEntity proEntity = sceneService.findById(id);
+        if (proEntity != null) {
+            saveLog("我的场景", "删除场景:"+ proEntity.getSceneName());
+        }
+
         sceneService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     /**
@@ -75,13 +85,21 @@ public class PersonalCenterController extends BaseController {
      * @return
      */
     @RequiresPermissions("admin:scene:edit")
-    @WebControllerLog(description = "个人中心-我的场景/编辑")
+//    @WebControllerLog(description = "个人中心-我的场景/编辑")
     @ApiOperation("编辑场景")
     @GetMapping("scene/edit/{id}")
     public ResultJson edit(@PathVariable Long id){
         SceneProEntity proEntity = sceneService.findById(id);
+
+        if (proEntity == null) {
+            return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
+        }
+
+
         String webSite = proEntity.getWebSite();
         webSite = webSite.replace("showProMobile", "editProMobile");
+
+        saveLog("我的场景", "编辑场景:"+ proEntity.getSceneName());
         return new ResultJson(MsgCode.SUCCESS_CODE, webSite);
     }
 
@@ -118,7 +136,7 @@ public class PersonalCenterController extends BaseController {
     @GetMapping("camera/save/{code}")
     public ResultJson save(@PathVariable String code){
         if(StringUtils.isEmpty(code)){
-            return new ResultJson(MsgCode.FAILURE_CODE_3001, MsgCode.FAILURE_MSG_3001);
+            return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
         }
 
 
@@ -133,9 +151,10 @@ public class PersonalCenterController extends BaseController {
             cameraService.save(cameraEntity);
         }
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 
 
+
 }

+ 2 - 2
xiaoan-web/src/main/java/com/xiaoan/web/backend/ResourceController.java

@@ -69,7 +69,7 @@ public class ResourceController {
 
         resourceService.save(resourceEntity);
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @ApiOperation("查询资源信息")
@@ -83,7 +83,7 @@ public class ResourceController {
     @GetMapping("delete/{id}")
     public ResultJson delete(@PathVariable Long id){
         resourceService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 

+ 5 - 4
xiaoan-web/src/main/java/com/xiaoan/web/backend/RoleController.java

@@ -144,7 +144,8 @@ public class RoleController extends BaseController {
         } else {
             roleEntity = roleService.findById(param.getId());
             if (roleEntity == null) {
-                return new ResultJson(MsgCode.FAILURE_CODE_3002, MsgCode.FAILURE_MSG_3002);
+                return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
+
             }
             BeanUtils.copyProperties(param, roleEntity);
             roleEntity.setUpdateTime(new Date());
@@ -160,7 +161,7 @@ public class RoleController extends BaseController {
                 for (long i : param.getResources()) {
                     roleService.saveRoleResource(roleEntity.getId(), i);
                 }
-                return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+                return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
             }
         }
 
@@ -173,7 +174,7 @@ public class RoleController extends BaseController {
     @GetMapping("delete/{id}")
     public ResultJson delete(@PathVariable Long id){
         roleService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @WebControllerLog(description = "角色权限-多角色删除")
@@ -182,7 +183,7 @@ public class RoleController extends BaseController {
     @GetMapping("delete/all/{ids}")
     public ResultJson delete(@PathVariable String ids){
         roleService.deleteByIds(ids);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 

+ 9 - 8
xiaoan-web/src/main/java/com/xiaoan/web/backend/UserController.java

@@ -72,7 +72,8 @@ public class UserController extends BaseController {
 
             entity = userService.findById(param.getId());
             if (entity == null) {
-                return new ResultJson(MsgCode.FAILURE_CODE_3002, MsgCode.FAILURE_MSG_3002);
+                return new ResultJson(MsgCode.e_COMMON_3001, MsgCode.msg_COMMON_3001);
+
             }
             // 每次修改,删除用户角色表信息,重新添加
             userService.deleteUserRole(param.getId());
@@ -112,7 +113,7 @@ public class UserController extends BaseController {
             if (param.getRoleId() != null) {
                 // 一个用户只有一个角色
                 userService.saveUserRole(entity.getId(), param.getRoleId());
-                return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+                return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
             }
         }
         return new ResultJson(MsgCode.ERROR_CODE, MsgCode.ERROR_MSG);
@@ -123,7 +124,7 @@ public class UserController extends BaseController {
     @GetMapping("delete/{id}")
     public ResultJson delete(@PathVariable Long id){
         userService.deleteById(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @RequiresRoles(value = {"admin"}, logical = Logical.OR)
@@ -131,7 +132,7 @@ public class UserController extends BaseController {
     @GetMapping("delete/all/{id}")
     public ResultJson deleteAll(@PathVariable String id){
         userService.deleteByIds(id);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
 
@@ -150,12 +151,12 @@ public class UserController extends BaseController {
         // 验证原密码
         String decryptName = PasswordUtils.decrypt(userEntity.getPassword(), oldPassword, PasswordUtils.getStaticSalt());
         if (!userEntity.getUserName().equals(decryptName)) {
-            return new ResultJson(MsgCode.FAILURE_CODE_4002, MsgCode.FAILURE_MSG_4002);
+            return new ResultJson(MsgCode.e_ADMIN_4002, MsgCode.msg_ADMIN_4002);
         }
 
         userEntity.setPassword(PasswordUtils.encrypt(userEntity.getUserName(), password, PasswordUtils.getStaticSalt()));
         userService.update(userEntity);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @WebControllerLog(description = "用户管理-重置密码")
@@ -166,7 +167,7 @@ public class UserController extends BaseController {
         UserEntity userEntity = userService.findById(id);
         userEntity.setPassword(PasswordUtils.encrypt(userEntity.getUserName(), "123456", PasswordUtils.getStaticSalt()));
         userService.update(userEntity);
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     @WebControllerLog(description = "用户管理-多重置密码")
@@ -184,7 +185,7 @@ public class UserController extends BaseController {
         }
 
 
-        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.SUCCESS_MSG);
+        return new ResultJson(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
     }
 
     public static void main(String[] args) {

+ 56 - 19
xiaoan-web/src/main/java/com/xiaoan/web/shiro/JWTFilter.java

@@ -1,5 +1,8 @@
 package com.xiaoan.web.shiro;
 
+import com.alibaba.fastjson.JSONObject;
+import com.xiaoan.common.exception.BaseRuntimeException;
+import com.xiaoan.common.exception.JwtAuthenticationException;
 import lombok.extern.log4j.Log4j2;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.shiro.authc.AuthenticationException;
@@ -12,6 +15,7 @@ import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
+import java.io.PrintWriter;
 
 
 /**
@@ -35,7 +39,9 @@ public class JWTFilter extends BasicHttpAuthenticationFilter {
             log.info("error Authorization is null");
 
             // 先这样抛出异常,这个种不是接口的形式
-            throw new AuthenticationException("Authorization is null ");
+            throw new AuthenticationException("token is null");
+//            throw new JwtAuthenticationException(5001, "Authorization is null");
+//            throw new BaseRuntimeException(5001, "token is null");
         }
 
         return true;
@@ -49,18 +55,13 @@ public class JWTFilter extends BasicHttpAuthenticationFilter {
      */
     @Override
     protected boolean executeLogin(ServletRequest request, ServletResponse response) {
-//        LOGGER.warn("run executeLogin");
         HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         String authorization = httpServletRequest.getHeader("Authorization");
         JWTToken token = new JWTToken(authorization);
 
-        // 判断token 是否跟redis
-
         // 提交给realm进行登入,如果错误他会抛出异常并被捕获
         getSubject(request, response).login(token);
 
-
-
         // 如果没有抛出异常则代表登入成功,返回true
         return true;
     }
@@ -81,16 +82,30 @@ public class JWTFilter extends BasicHttpAuthenticationFilter {
      */
     @Override
     protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
-//        LOGGER.warn("run isAccessAllowed");
         if (isLoginAttempt(request, response)) {
-//            try {
-//                executeLogin(request, response);
-//            } catch (Exception e) {
-////                response401(request, response);
-//                throw new AuthenticationException("Authorization is null 123");
-//            }
-
-            executeLogin(request, response);
+            try {
+                executeLogin(request, response);
+
+            } catch (Exception e) {
+                /** 这个异常需要自己写,全局捕获不了*/
+
+                // 认证出现异常,传递错误信息msg
+                String msg = e.getMessage();
+                // 获取应用异常(该Cause是导致抛出此throwable(异常)的throwable(异常))
+                Throwable throwable = e.getCause();
+                JSONObject jsonObject = new JSONObject();
+                if (throwable instanceof JwtAuthenticationException) {
+                    jsonObject.put("status", ((JwtAuthenticationException) throwable).getCode());
+                    jsonObject.put("message", ((JwtAuthenticationException) throwable).getMsg());
+                }else{
+                    log.error(msg);
+                    jsonObject.put("status", 5002);
+                    jsonObject.put("message", "token invalid");
+                }
+                // 直接返回Response信息
+                this.writeResponse(response, jsonObject);
+                return false;
+            }
         }
         // return false 前端没有响应,接收不到异常
         return true;
@@ -119,12 +134,34 @@ public class JWTFilter extends BasicHttpAuthenticationFilter {
     /**
      * 将非法请求跳转到 /401
      */
-    private void response401(ServletRequest req, ServletResponse resp) {
+//    private void response401(ServletRequest req, ServletResponse resp) {
+//        try {
+//            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
+//            httpServletResponse.sendRedirect("/401");
+//        } catch (IOException e) {
+//            log.error(e.getMessage());
+//        }
+//    }
+
+    /**
+     * 无需转发,直接返回Response信息
+     *
+     */
+    private void writeResponse(ServletResponse response, JSONObject msg) {
+        response.setCharacterEncoding("UTF-8");
+        response.setContentType("application/json; charset=utf-8");
+        PrintWriter out = null;
         try {
-            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
-            httpServletResponse.sendRedirect("/401");
+            out = response.getWriter();
+            out.append(msg.toString());
+            out.flush();
+            out.close();
         } catch (IOException e) {
-            log.error(e.getMessage());
+            e.printStackTrace();
+        } finally {
+            if (out != null){
+                out.close();
+            }
         }
     }
 }

+ 9 - 14
xiaoan-web/src/main/java/com/xiaoan/web/shiro/MyRealm.java

@@ -1,5 +1,6 @@
 package com.xiaoan.web.shiro;
 
+import com.xiaoan.common.exception.JwtAuthenticationException;
 import com.xiaoan.domain.backend.ResourceEntity;
 import com.xiaoan.domain.backend.RoleEntity;
 import com.xiaoan.domain.backend.UserEntity;
@@ -111,44 +112,38 @@ public class MyRealm extends AuthorizingRealm {
      */
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
-//        log.warn("run doGetAuthenticationInfo");
         String token = (String) auth.getCredentials();
-//        log.warn("token: {}", token);
         // 解密获得username,用于和数据库进行对比
-//        String username = JWTUtil.getUsername(token);
         String username = JwtUtil2.getUsername(token);
         if (username == null) {
             log.info("error token username");
-            throw new AuthenticationException("token invalid");
+//            throw new AuthenticationException("token invalid");
+            throw new JwtAuthenticationException(5001, "token invalid");
         }
 
         UserEntity userEntity = userService.findByUserName(username);
         if (userEntity == null) {
             log.info("error token userEntity");
-            throw new AuthenticationException("UserEntity didn't existed!");
+//            throw new AuthenticationException("UserEntity didn't existed!");
+            throw new JwtAuthenticationException(5001, "User didn't existed!");
         }
 
         // 校验请求token是否跟redis token一致
         String redisToken = redisTemplate.opsForValue().get(userEntity.getUserName());
-//        log.warn("redisToken: {}", redisToken);
         if (!token.equals(redisToken)) {
             log.info("error token redis");
-            throw new AuthenticationException("token invalid");
+//            throw new AuthenticationException("token invalid");
+            throw new JwtAuthenticationException(5001, "token invalid");
 
         }
 
 
-//        if (! JWTUtil.verify(token, username, userEntity.getPassword())) {
-//            log.info("error token username or password");
-//            throw new AuthenticationException("token invalid");
-//        }
-
         if (! JwtUtil2.isVerify(token, username)) {
             log.info("error token username or password");
-            throw new AuthenticationException("token invalid");
+//            throw new AuthenticationException("token invalid");
+            throw new JwtAuthenticationException(5001, "token invalid");
         }
 
-//        log.warn("end doGetAuthenticationInfo");
 
         return new SimpleAuthenticationInfo(token, token, "my_realm");
     }