You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入负数显示错误提示:货币转换器开发及Promise catch可行性咨询

问题解答

核心疑问回复

  • 负数输入校验的场景不适合用Promise.catch处理:catch是用来捕获异步操作(比如接口请求失败、网络异常、JSON解析错误)的异常,输入负数属于前端本地的表单业务校验逻辑,直接在发请求前做判断处理即可,不需要强行包装成Promise错误走catch链路,反而会增加代码复杂度。

实现方案

第一步:修改HTML

  1. 给第二个金额输入框也加上min="0"属性,限制用户输入负数
  2. 新增错误提示展示容器
<!-- 原有p标签下面新增错误提示 -->
<p>Choose the currency and the amount</p>
<div id="error-tip" style="color: #dc2626; display: none; margin: 8px 0;">输入金额不能为负数</div>
<!-- 第二个输入框加min属性 -->
<input type="number" min="0" id="amount-two">

第二步:修改Javascript逻辑

在calculate函数最前面先做本地金额校验,校验不通过直接展示提示、终止后续请求逻辑;同时给fetch加上catch处理真实的请求异常。
修改后的完整JS代码:

const currencyOne = document.querySelector('#currency-one');
const currencyTwo = document.querySelector('#currency-two');
const amountOne = document.querySelector('#amount-one');
const amountTwo = document.querySelector('#amount-two');
const swapButton = document.querySelector('.btn');
const rateEl = document.querySelector('.rate');
const errorTip = document.querySelector('#error-tip');

//Calculate function to fetch currency rates
function calculate(){
    // 先做金额校验
    const amountVal = Number(amountOne.value);
    if (amountVal < 0) {
        errorTip.style.display = 'block';
        amountTwo.value = '';
        rateEl.innerHTML = '';
        return;
    }
    // 校验通过隐藏错误提示
    errorTip.style.display = 'none';

    const currency_one = currencyOne.value;
    const currency_two = currencyTwo.value;
    fetch(`https://v6.exchangerate-api.com/v6/0a8724f8d325969fedf0f714/latest/${currency_one}`)
   .then(res => res.json())
   .then(data =>{
        const rate = data.conversion_rates[currency_two];
        rateEl.innerHTML = `1 ${currency_one} = ${rate} ${currency_two}`;
        amountTwo.value = (amountVal * rate).toFixed(2);
    })
    // 这里的catch才是处理请求相关的异常
   .catch(err => {
        errorTip.innerText = '汇率查询失败,请稍后重试';
        errorTip.style.display = 'block';
    })
}

//event listener for currency element 1
currencyOne.addEventListener('change',calculate);
currencyTwo.addEventListener('change',calculate);
amountOne.addEventListener('input',calculate);
amountTwo.addEventListener('input',calculate);

swapButton.addEventListener('click',function(){
    const temp = currencyOne.value;
    currencyOne.value = currencyTwo.value;
    currencyTwo.value = temp;
    calculate();
})
calculate();

补充说明

  • input的min="0"属性只能限制点击上下箭头时不能选负数,用户手动输入负数还是能输入,所以必须加JS校验逻辑兜底
  • 额外加的fetch catch是用来处理接口请求失败的场景,和本地校验逻辑分开,职责更清晰

内容的提问来源于stack exchange,提问作者M. R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:06:03