Normal operation

Async saveSql() {if (this.sql === "") {this.$message.error(' SQL cannot be empty ') return} Prompts and terminates the execution of if (! Return} await dbapi.savesqL. request({id: this.dbId, SQL: this. SQL, type: this. 1}) this.$message.success(' save successfully ')}Copy the code

Appeal this way obviously the code is more redundant, and cumbersome.

Assertion mode processing

  1. Create a new assert.ts file in the common directory
/** * inconsistent business assertion error. */ class AssertError extends Error {constructor(message: string) { super(message); // (1) // Error class name this.name = "AssertError"; } /** * the object is notNull or undefiend ** @param obj object * @param MSG error message */ (string) {if obj = = null | | obj = = undefined) {throw new AssertError (MSG)}} / assert that can't be empty string * * * * * @ param string STR * */ export function notEmpty(STR: string, MSG: string) { if (str == null || str == undefined || str == '') { throw new AssertError(msg); }} /** ** @param obj1 * @param obj2 * @param MSG error message */ export function isEquals(obj1: any, obj2: any, msg: string) { if (obj1 ! == obj2) { throw new AssertError(msg); }} /** * if (condition: condition) {if (condition: condition) {if (condition: condition) {if (condition: condition) {if (condition: condition) {if (condition: condition); boolean, msg: string) { if (! condition) { throw new AssertError(msg); }}Copy the code
  1. Main. ts added vUE global error handlers
Vue. Config. errorHandler = function(err, vm,info) { If (err.name == 'AssertError') {elementui.message. error(err.message)} else {// Otherwise console prints error Message console.error(err,  info) } }Copy the code
  1. Use assert
Import {notEmpty, notNull} from '@/common/assert' async saveSql() { Savesql. request({id: this.dbId, SQL: {id: this.dbId, SQL: {id: this.dbId, SQL: {id: this.dbId, SQL: {id: this.dbId, SQL: {id: this.dbId, SQL: {id: this.dbId, SQL: {id: this. This. SQL, type: 1}) this.$message.success(' saved successfully ')}Copy the code

Conclusion: Using assertions can simplify a lot of repetitive code, focus on business processes, and be more comfortable.