Unverified Commit 0116c112 authored by gaoyan's avatar gaoyan Committed by GitHub

Modified the logic of the error pop-up window (#2690)

* Modified the logic of the error pop-up window * Modified the logic of the error pop-up window
parent 65bbe7bf
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.aop.exception;
import org.dinky.data.result.Result;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ControllerAdvice
@Order
public class UnKnownExceptionHandler {
@ExceptionHandler
public Result<Exception> unknownException(Exception e) {
return Result.exception(e.getMessage(), e);
}
}
...@@ -17,9 +17,8 @@ ...@@ -17,9 +17,8 @@
* *
*/ */
package org.dinky.aop; package org.dinky.aop.exception;
import org.dinky.data.enums.CodeEnum;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.exception.BusException; import org.dinky.data.exception.BusException;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
...@@ -32,8 +31,8 @@ import java.util.Map; ...@@ -32,8 +31,8 @@ import java.util.Map;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger; import org.springframework.core.Ordered;
import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError; import org.springframework.validation.FieldError;
...@@ -55,10 +54,9 @@ import cn.hutool.core.util.StrUtil; ...@@ -55,10 +54,9 @@ import cn.hutool.core.util.StrUtil;
* @since 2022/2/2 22:22 * @since 2022/2/2 22:22
*/ */
@RestControllerAdvice @RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebExceptionHandler { public class WebExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(WebExceptionHandler.class);
@ExceptionHandler @ExceptionHandler
public Result<Void> busException(BusException e) { public Result<Void> busException(BusException e) {
if (StrUtil.isEmpty(e.getMsg())) { if (StrUtil.isEmpty(e.getMsg())) {
...@@ -83,12 +81,12 @@ public class WebExceptionHandler { ...@@ -83,12 +81,12 @@ public class WebExceptionHandler {
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse(); HttpServletResponse response = servletRequestAttributes.getResponse();
if (response != null) { if (response != null) {
response.setStatus(CodeEnum.NOTLOGIN.getCode()); response.setStatus(HttpStatus.UNAUTHORIZED.value());
} }
String type = notLoginException.getType(); String type = notLoginException.getType();
Status status = ERR_CODE_MAPPING.getOrDefault(type, Status.NOT_TOKEN); Status status = ERR_CODE_MAPPING.getOrDefault(type, Status.NOT_TOKEN);
return Result.failed(status); return Result.authorizeFailed(status);
} }
/** /**
...@@ -108,19 +106,13 @@ public class WebExceptionHandler { ...@@ -108,19 +106,13 @@ public class WebExceptionHandler {
// 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可 // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
FieldError fieldError = (FieldError) errors.get(0); FieldError fieldError = (FieldError) errors.get(0);
if (StringUtils.isNotBlank(fieldError.getDefaultMessage())) { if (StringUtils.isNotBlank(fieldError.getDefaultMessage())) {
return Result.failed( return Result.paramsError(
Status.GLOBAL_PARAMS_CHECK_ERROR, fieldError.getField(), fieldError.getDefaultMessage()); Status.GLOBAL_PARAMS_CHECK_ERROR, fieldError.getField(), fieldError.getDefaultMessage());
} }
return Result.failed( return Result.paramsError(
Status.GLOBAL_PARAMS_CHECK_ERROR_VALUE, fieldError.getField(), fieldError.getRejectedValue()); Status.GLOBAL_PARAMS_CHECK_ERROR_VALUE, fieldError.getField(), fieldError.getRejectedValue());
} }
} }
return Result.failed(Status.REQUEST_PARAMS_ERROR); return Result.paramsError(Status.REQUEST_PARAMS_ERROR);
}
@ExceptionHandler
public Result<Void> unknownException(Exception e) {
logger.error("ERROR:", e);
return Result.failed(Status.UNKNOWN_ERROR, (Object) e.getMessage());
} }
} }
...@@ -24,6 +24,7 @@ import org.dinky.data.enums.Status; ...@@ -24,6 +24,7 @@ import org.dinky.data.enums.Status;
import java.io.Serializable; import java.io.Serializable;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.Objects;
import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateTime;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
...@@ -43,7 +44,9 @@ import lombok.NoArgsConstructor; ...@@ -43,7 +44,9 @@ import lombok.NoArgsConstructor;
@ApiModel(value = "Result", description = "Return Result") @ApiModel(value = "Result", description = "Return Result")
public class Result<T> implements Serializable { public class Result<T> implements Serializable {
/** result data */ /**
* result data
*/
@ApiModelProperty( @ApiModelProperty(
value = "Result Data", value = "Result Data",
name = "data", name = "data",
...@@ -59,7 +62,7 @@ public class Result<T> implements Serializable { ...@@ -59,7 +62,7 @@ public class Result<T> implements Serializable {
dataType = "Integer", dataType = "Integer",
required = true, required = true,
example = "0", example = "0",
notes = "0: success, 1: fail") notes = "CodeEnum")
private Integer code; private Integer code;
@ApiModelProperty( @ApiModelProperty(
...@@ -70,7 +73,10 @@ public class Result<T> implements Serializable { ...@@ -70,7 +73,10 @@ public class Result<T> implements Serializable {
example = "success", example = "success",
notes = "success: success, fail: fail") notes = "success: success, fail: fail")
private String msg; private String msg;
/** result time */
/**
* result time
*/
@ApiModelProperty( @ApiModelProperty(
value = "Result Time", value = "Result Time",
name = "time", name = "time",
...@@ -79,7 +85,10 @@ public class Result<T> implements Serializable { ...@@ -79,7 +85,10 @@ public class Result<T> implements Serializable {
example = "2021-05-03 19:56:00", example = "2021-05-03 19:56:00",
notes = "yyyy-MM-dd HH:mm:ss") notes = "yyyy-MM-dd HH:mm:ss")
private String time; private String time;
/** result success */
/**
* result success
*/
@ApiModelProperty( @ApiModelProperty(
value = "Result is Success", value = "Result is Success",
name = "success", name = "success",
...@@ -148,11 +157,17 @@ public class Result<T> implements Serializable { ...@@ -148,11 +157,17 @@ public class Result<T> implements Serializable {
} }
public static <T> Result<T> of(T data, Integer code, String msg) { public static <T> Result<T> of(T data, Integer code, String msg) {
return new Result<>(data, code, msg, new DateTime().toString(), code == 0); return new Result<>(
data, code, msg, new DateTime().toString(), Objects.equals(code, CodeEnum.SUCCESS.getCode()));
} }
public static <T> Result<T> of(T data, Integer code, Status status) { public static <T> Result<T> of(T data, Integer code, Status status) {
return new Result<>(data, code, status.getMessage(), new DateTime().toString(), code == 0); return new Result<>(
data,
code,
status.getMessage(),
new DateTime().toString(),
Objects.equals(code, CodeEnum.SUCCESS.getCode()));
} }
public static <T> Result<T> failed() { public static <T> Result<T> failed() {
...@@ -183,11 +198,27 @@ public class Result<T> implements Serializable { ...@@ -183,11 +198,27 @@ public class Result<T> implements Serializable {
return of(model, CodeEnum.ERROR.getCode(), status.getMessage()); return of(model, CodeEnum.ERROR.getCode(), status.getMessage());
} }
public static <T> Result<T> authorizeFailed(Status status) {
return of(null, CodeEnum.AUTHORIZE_ERROR.getCode(), status.getMessage());
}
public static <T> Result<T> authorizeFailed(String msg) {
return of(null, CodeEnum.AUTHORIZE_ERROR.getCode(), msg);
}
public static Result<Exception> exception(String msg, Exception e) {
return of(e, CodeEnum.EXCEPTION.getCode(), msg);
}
public static <T> Result<T> paramsError(Status status, Object... args) {
return of(null, CodeEnum.PARAMS_ERROR.getCode(), MessageFormat.format(status.getMessage(), args));
}
/** /**
* Call this function if there is any error * Call this function if there is any error
* *
* @param status status * @param status status
* @param args args * @param args args
* @return result * @return result
*/ */
public static <T> Result<T> errorWithArgs(Status status, Object... args) { public static <T> Result<T> errorWithArgs(Status status, Object... args) {
......
...@@ -177,19 +177,19 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -177,19 +177,19 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
user = loginDTO.isLdapLogin() ? ldapLogin(loginDTO) : localLogin(loginDTO); user = loginDTO.isLdapLogin() ? ldapLogin(loginDTO) : localLogin(loginDTO);
} catch (AuthException e) { } catch (AuthException e) {
// Handle authentication exceptions and return the corresponding error status // Handle authentication exceptions and return the corresponding error status
return Result.failed(e.getStatus() + e.getMessage()); return Result.authorizeFailed(e.getStatus() + e.getMessage());
} }
// Check if the user is enabled // Check if the user is enabled
if (!user.getEnabled()) { if (!user.getEnabled()) {
loginLogService.saveLoginLog(user, Status.USER_DISABLED_BY_ADMIN); loginLogService.saveLoginLog(user, Status.USER_DISABLED_BY_ADMIN);
return Result.failed(Status.USER_DISABLED_BY_ADMIN); return Result.authorizeFailed(Status.USER_DISABLED_BY_ADMIN);
} }
UserDTO userInfo = refreshUserInfo(user); UserDTO userInfo = refreshUserInfo(user);
if (Asserts.isNullCollection(userInfo.getTenantList())) { if (Asserts.isNullCollection(userInfo.getTenantList())) {
loginLogService.saveLoginLog(user, Status.USER_NOT_BINDING_TENANT); loginLogService.saveLoginLog(user, Status.USER_NOT_BINDING_TENANT);
return Result.failed(Status.USER_NOT_BINDING_TENANT); return Result.authorizeFailed(Status.USER_NOT_BINDING_TENANT);
} }
// Perform login using StpUtil (Assuming it handles the session management) // Perform login using StpUtil (Assuming it handles the session management)
......
...@@ -29,7 +29,8 @@ public enum CodeEnum { ...@@ -29,7 +29,8 @@ public enum CodeEnum {
ERROR(1), ERROR(1),
EXCEPTION(5), EXCEPTION(5),
NOTLOGIN(401); PARAMS_ERROR(6),
AUTHORIZE_ERROR(7);
private Integer code; private Integer code;
......
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
export default { export default {
'app.response.response-error': 'ResponseError', 'app.response.response-error': 'ResponseError',
'app.response.sucess': 'Success', 'app.response.sucess': 'Success',
'app.response.error': 'Error', 'app.response.error': 'The operation was unsuccessful',
'app.response.exception': 'Server exception', 'app.response.exception': 'Server exception',
'app.response.notlogin': 'Not Login', 'app.response.notlogin': 'Authentication failed',
'app.response.notexist': 'you visit the page or interface does not exist' 'app.response.notexist': 'you visit the page or interface does not exist'
}; };
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
export default { export default {
'app.response.response-error': '响应出错', 'app.response.response-error': '响应出错',
'app.response.sucess': '成功', 'app.response.sucess': '成功',
'app.response.error': '错误', 'app.response.error': '操作未成功',
'app.response.exception': '服务端错误', 'app.response.exception': '服务端错误',
'app.response.notlogin': '未登录', 'app.response.notlogin': '身份认证失败',
'app.response.notexist': '你访问的页面/接口不存在' 'app.response.notexist': '你访问的页面/接口不存在'
}; };
...@@ -19,27 +19,50 @@ ...@@ -19,27 +19,50 @@
import { API_CONSTANTS } from '@/services/endpoints'; import { API_CONSTANTS } from '@/services/endpoints';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
import { ErrorNotification } from '@/utils/messages'; import { ErrorNotification, WarningNotification } from '@/utils/messages';
import { history } from '@@/core/history'; import { history } from '@@/core/history';
import type { RequestOptions } from '@@/plugin-request/request'; import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max'; import type { RequestConfig } from '@umijs/max';
// 错误处理方案: 错误类型 // 错误处理方案: 错误类型
enum ErrorCode { enum ErrorCode {
'app.response.sucess' = 0, SUCCESS = 0,
'app.response.error' = 1, ERROR = 1,
'app.response.exception' = 5, EXCEPTION = 5,
'app.response.notlogin' = 401 PARAMS_ERROR = 6,
AUTHORIZE_ERROR = 7
} }
// 与后端约定的响应数据格式 // 与后端约定的响应数据格式
interface ResponseStructure { interface ResponseStructure {
success: boolean; success: boolean;
data?: boolean; data?: any;
code: number; code: number;
msg: string; msg: string;
} }
const handleBizError = (result: ResponseStructure) => {
const { msg, code, data } = result;
switch (code) {
case ErrorCode.SUCCESS:
//don't deal with it, just be happy
break;
case ErrorCode.ERROR:
WarningNotification(msg, l('app.response.error'));
break;
case ErrorCode.EXCEPTION:
//TODO 可配置化,dev换弹出错误,release不弹
//ErrorNotification(JSON.stringify(data), l('app.response.error'));
break;
case ErrorCode.PARAMS_ERROR:
ErrorNotification(msg, l('app.response.error'));
break;
case ErrorCode.AUTHORIZE_ERROR:
ErrorNotification(msg, l('app.response.notlogin'));
break;
}
};
/** /**
* @name 错误处理 * @name 错误处理
* pro 自带的错误处理, 可以在这里做自己的改动 * pro 自带的错误处理, 可以在这里做自己的改动
...@@ -65,8 +88,7 @@ export const errorConfig: RequestConfig = { ...@@ -65,8 +88,7 @@ export const errorConfig: RequestConfig = {
if (error.name === 'BizError') { if (error.name === 'BizError') {
const errorInfo: ResponseStructure = error.info; const errorInfo: ResponseStructure = error.info;
if (errorInfo) { if (errorInfo) {
const { msg, code } = errorInfo; handleBizError(errorInfo);
ErrorNotification(msg, l(ErrorCode[code], 'Error'));
} }
} else if (error.response) { } else if (error.response) {
// 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围 // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
...@@ -75,7 +97,8 @@ export const errorConfig: RequestConfig = { ...@@ -75,7 +97,8 @@ export const errorConfig: RequestConfig = {
history.push(API_CONSTANTS.LOGIN_PATH); history.push(API_CONSTANTS.LOGIN_PATH);
} else { } else {
//预留,处理其他code逻辑,目前未定义的code统一发送错误通知 //预留,处理其他code逻辑,目前未定义的code统一发送错误通知
ErrorNotification(error.message, error.code); //TODO 可配置化,dev换弹出错误,release不弹
// ErrorNotification(error.message, error.code);
} }
} else if (error.request) { } else if (error.request) {
// 请求已经成功发起,但没有收到响应 // 请求已经成功发起,但没有收到响应
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment