Browse Source

模型增加通用鉴权异常,并在api层附带特殊处理状态码

Signed-off-by: luoshi <luoshi@qmth.com.cn>
luoshi 3 years ago
parent
commit
de8f1b7d4a

+ 18 - 0
core-models/src/main/java/com/qmth/boot/core/exception/UnauthorizedException.java

@@ -0,0 +1,18 @@
+package com.qmth.boot.core.exception;
+
+/**
+ * 未授权的运行时异常,在API层会按401状态码处理
+ */
+public class UnauthorizedException extends RuntimeException {
+
+    private static final long serialVersionUID = 1957446799072827901L;
+
+    public UnauthorizedException(String message) {
+        super(message);
+    }
+
+    public UnauthorizedException(String message, Throwable t) {
+        super(message, t);
+    }
+
+}

+ 7 - 0
starter-api/src/main/java/com/qmth/boot/api/exception/GlobalExceptionHandler.java

@@ -2,6 +2,7 @@ package com.qmth.boot.api.exception;
 
 import com.qmth.boot.core.exception.ReentrantException;
 import com.qmth.boot.core.exception.StatusException;
+import com.qmth.boot.core.exception.UnauthorizedException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.http.HttpHeaders;
@@ -26,6 +27,12 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
         return new ResponseEntity<>(e.responseEntity(), new HttpHeaders(), e.getStatus());
     }
 
+    @ExceptionHandler(UnauthorizedException.class)
+    public ResponseEntity<Object> handleUnauthorizedException(UnauthorizedException e) {
+        //log.error(e.getMessage(), e);
+        return handleApiException(DefaultExceptionEnum.AUTHORIZATION_ERROR.exception(e.getMessage()));
+    }
+
     @ExceptionHandler(ReentrantException.class)
     public ResponseEntity<Object> handleReentrantException(ReentrantException e) {
         //log.error(e.getMessage(), e);