在vue使用異常處理做錯誤提示

lyxxxh發表於2020-07-20

新增程式碼

Vue.prototype.errorMsg = function(message, code)
{
  alert(message);
// Vue.$vux.toast.show({ 我用vux的,看自己情況自定義錯誤資訊
//    text: message,
//  type: 'warn'
//  })
}

Vue.config.errorHandler = (err, vm, info) => {
  if( err instanceof vm.errorMsg)  // 不讓瀏覽器顯示自定義異常的資訊
  return true;
}

使用

if( true)
throw  new this.errorMsg('請改成false')
alert("這個不會執行了");

為啥要用異常

異常可以停止後面的程式碼執行,簡單多了。

看到好多的專案都是:

if( true){
  alert("請改成false")
  return;
}
alert("這個不會執行了");

多了個return ;不嫌麻煩嗎? (每次都要寫return ;)

而且還沒有能統一管理的入口 。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

專心學習不瞎搞

相關文章