hejianhao
2026-09-01 f4e8dfd7f8f11966f4b5dc8c6661cbc3feccc4cf
tcm-training-admin-backend/src/main/java/com/tcm/training/admin/utils/MsgUtils.java
@@ -49,13 +49,20 @@
    }
    /**
     * 发送阿里云短信验证码。
     * 创建阿里云短信客户端,便于测试覆盖异常分支。
     */
    public void sendMsg(String phone, Map<String,String> params, String templateCode, String signName) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = MsgUtils.createClient(
    protected com.aliyun.dysmsapi20170525.Client createSmsClient() throws Exception {
        return MsgUtils.createClient(
                properties.getAccessKeyId(),
                properties.getAccessKeySecret()
        );
    }
    /**
     * 发送阿里云短信验证码。
     */
    public void sendMsg(String phone, Map<String,String> params, String templateCode, String signName) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createSmsClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
@@ -73,18 +80,36 @@
            }
            log.info("阿里云短信发送成功,templateCode={}, statusCode={}", templateCode, sendSmsResponse.getStatusCode());
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("阿里云短信发送失败,templateCode={}, message={}", templateCode, error.message);
            log.error("阿里云短信发送失败,templateCode={}, code={}, message={}",
                    templateCode,
                    error.getCode(),
                    resolveExceptionMessage(error, "阿里云短信发送失败"),
                    error);
            throw new IllegalStateException("短信发送失败,请稍后重试");
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("阿里云短信发送异常,templateCode={}, message={}", templateCode, error.message);
        } catch (Exception error) {
            log.error("阿里云短信发送异常,templateCode={}, message={}",
                    templateCode,
                    resolveExceptionMessage(error, "阿里云短信发送异常"),
                    error);
            throw new IllegalStateException("短信发送失败,请稍后重试");
        }
    }
    /**
     * 安全读取异常文案,避免阿里云 SDK 异常 message 为空时二次抛错。
     */
    private String resolveExceptionMessage(Throwable error, String fallback) {
        if (error == null) {
            return fallback;
        }
        String message = error.getMessage();
        if (message == null || message.trim().isEmpty()) {
            return fallback;
        }
        return message;
    }
    /**
     * 将模板变量转换为阿里云要求的 JSON 字符串。
     */
    private String toTemplateParam(Map<String, String> params) throws JsonProcessingException {