Files
mayfly-go/frontend/src/common/assert.ts

90 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-11-21 13:20:45 +08:00
import { i18n } from '@/i18n';
2021-01-08 15:37:32 +08:00
/**
*
*/
class AssertError extends Error {
constructor(message: string) {
super(message);
2021-01-08 15:37:32 +08:00
// 错误类名
this.name = 'AssertError';
2021-01-08 15:37:32 +08:00
}
}
/**
* true
*
* @param condition
* @param msg
2021-01-08 15:37:32 +08:00
*/
export function isTrue(condition: boolean, msg: string) {
if (!condition) {
throw new AssertError(msg);
2021-01-08 15:37:32 +08:00
}
}
/**
* null,0,''
*
* @param obj 1
* @param msg
*/
export function notBlank(obj: any, msg: string) {
isTrue(obj, msg);
2021-01-08 15:37:32 +08:00
}
2024-11-21 13:20:45 +08:00
/**
* null,0,''
*
* @param obj
* @param field i18n msgKey
*/
export function notBlankI18n(obj: any, field: string) {
notBlank(obj, i18n.global.t('common.fieldNotEmpty', { field: i18n.global.t(field) }));
}
2021-01-08 15:37:32 +08:00
/**
*
*
2021-01-08 15:37:32 +08:00
* @param obj1 1
* @param obj2 2
* @param msg
*/
export function isEquals(obj1: any, obj2: any, msg: string) {
isTrue(obj1 === obj2, msg);
2021-01-08 15:37:32 +08:00
}
2022-02-07 17:49:48 +08:00
/**
* null或undefiend
*
* @param obj
* @param msg
2022-02-07 17:49:48 +08:00
*/
export function notNull(obj: any, msg: string) {
if (obj == null || obj == undefined) {
throw new AssertError(msg);
2022-02-07 17:49:48 +08:00
}
}
2021-01-08 15:37:32 +08:00
/**
*
*
* @param str
* @param msg
*/
export function notEmpty(str: string, msg: string) {
if (str == null || str == undefined || str == '') {
2021-01-08 15:37:32 +08:00
throw new AssertError(msg);
}
}
2024-11-21 13:20:45 +08:00
/**
*
*
* @param str
* @param field i18n msgKey
*/
export function notEmptyI18n(str: string, field: string) {
notEmpty(str, i18n.global.t('common.fieldNotEmpty', { field: i18n.global.t(field) }));
}