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

97 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-11-21 13:20:45 +08:00
import { i18n } from '@/i18n';
2026-05-19 21:25:28 +08:00
import { Msg } from '@/hooks/useI18n';
2024-11-21 13:20:45 +08:00
2021-01-08 15:37:32 +08:00
/**
*
*/
class AssertError extends Error {
constructor(message: string) {
2026-05-19 21:25:28 +08:00
Msg.error(message);
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 msgOrI18nKey i18n key
*/
export function isTrue(condition: boolean, msgOrI18nKey: string) {
if (!condition) {
throw new AssertError(i18n.global.t(msgOrI18nKey));
}
}
/**
* null,0,''
*
* @param obj 1
* @param msg
*/
export function notBlank(obj: any, msg: string) {
if (obj == null || obj == undefined || !obj) {
2024-11-26 17:32:44 +08:00
throw new AssertError(msg);
}
if (Array.isArray(obj) && obj.length == 0) {
throw new AssertError(msg);
}
}
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) }));
}
/**
*
*
* @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
/**
* null或undefiend
*
2021-01-08 15:37:32 +08:00
* @param obj
* @param msg
*/
export function notNull(obj: any, msg: string) {
if (obj == null || obj == undefined) {
throw new AssertError(msg);
2021-01-08 15:37:32 +08:00
}
}
/**
*
*
* @param str
* @param msg
*/
2021-01-08 15:37:32 +08:00
export function notEmpty(str: string, msg: string) {
if (str == null || str == undefined || str == '') {
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) }));
}