vue之?dāng)嘌苑绞叫r?yàn)參數(shù)并錯(cuò)誤提示

常規(guī)操作

 async saveSql() {
    // 如果sql內(nèi)容為空,則提示并結(jié)束執(zhí)行
    if (this.sql === '') {
      this.$message.error('sql內(nèi)容不能為空')
      return
    }
    // 如果Id為空,則提示并結(jié)束執(zhí)行
    if (!this.dbId) {
      this.$message.error('請(qǐng)先選擇數(shù)據(jù)庫(kù)')
      return
    }
    await dbApi.saveSql.request({ id: this.dbId, sql: this.sql, type: 1 })
    this.$message.success('保存成功')
  }

上訴該方式很明顯代碼比較冗余,且繁瑣。

斷言方式處理

  1. 在common目錄新建assert.ts文件
/**
 * 不符合業(yè)務(wù)斷言錯(cuò)誤。
 * 如果不自定義該錯(cuò)誤,vue全局錯(cuò)誤不好處理,無(wú)法判斷捕獲的錯(cuò)誤是不是要在控制臺(tái)打印錯(cuò)誤信息
 */
class AssertError extends Error {
    constructor(message: string) {
        super(message); // (1)
        // 錯(cuò)誤類(lèi)名
        this.name = "AssertError";
    }
}

/**
 * 斷言對(duì)象不為null或undefiend
 * 
 * @param obj 對(duì)象
 * @param msg 錯(cuò)誤提示
 */
export function notNull(obj: any, msg: string) {
    if (obj == null || obj == undefined) {
        throw new AssertError(msg)
    }
}

/**
* 斷言字符串不能為空
* 
* @param str 字符串
* @param msg 錯(cuò)誤提示
*/
export function notEmpty(str: string, msg: string) {
    if (str == null || str == undefined || str == '') {
        throw new AssertError(msg);
    }
}

/**
 * 斷言兩對(duì)象相等
 * 
 * @param obj1 對(duì)象1
 * @param obj2 對(duì)象2
 * @param msg 錯(cuò)誤消息
 */
export function isEquals(obj1: any, obj2: any, msg: string) {
    if (obj1 !== obj2) {
        throw new AssertError(msg);
    }
}

/**
 * 斷言表達(dá)式為true
 * 
 * @param obj1 對(duì)象1
 * @param obj2 對(duì)象2
 * @param msg 錯(cuò)誤消息
 */
export function isTrue(condition: boolean, msg: string) {
    if (!condition) {
        throw new AssertError(msg);
    }
}
  1. main.ts新增vue全局錯(cuò)誤處理函數(shù)
// 全局error處理
Vue.config.errorHandler = function(err, vm ,info) {
  // 如果是斷言錯(cuò)誤,則進(jìn)行提示即可
  if (err.name == 'AssertError') {
    ElementUI.Message.error(err.message)
  } else {
    // 否則控制臺(tái)打印錯(cuò)誤信息
    console.error(err, info)
  }
}
  1. 使用assert
// 導(dǎo)入對(duì)應(yīng)函數(shù)
import { notEmpty, notNull } from '@/common/assert'

async saveSql() {
    // 如果為空則會(huì)拋錯(cuò)誤,函數(shù)也會(huì)終止
    notEmpty(this.sql, 'sql內(nèi)容不能為空')
    notNull(this.dbId, '請(qǐng)先選擇數(shù)據(jù)庫(kù)')
    await dbApi.saveSql.request({ id: this.dbId, sql: this.sql, type: 1 })
    this.$message.success('保存成功')
  }

總結(jié):使用斷言的方式可以簡(jiǎn)化大量重復(fù)繁瑣的代碼,更加專注于業(yè)務(wù)處理,舒服不止一點(diǎn)點(diǎn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容