常規(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('保存成功')
}
上訴該方式很明顯代碼比較冗余,且繁瑣。
斷言方式處理
- 在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);
}
}
- 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)
}
}
- 使用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)。