Last active
March 18, 2021 03:46
-
-
Save Lxxyx/f7e35c0ff09fac32b642f64b8e000538 to your computer and use it in GitHub Desktop.
错误处理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
ValidationError, | |
AuthenticationError, | |
RoleError | |
} from './errors' | |
export function post (name: string) { | |
if (typeof name !== 'string') { | |
throw new ValidationError('name must be string') | |
} | |
const user = useSession() | |
if (!user) { | |
throw new AuthenticationError() | |
} | |
const role = useRole() | |
if (role !== 'admin') { | |
throw new RoleError('must be admin') | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
ValidationError, | |
AuthenticationError, | |
RoleError | |
} from './errors' | |
import { post } from '@/apis' | |
try { | |
await post(1) | |
} catch (e) { | |
if (e instanceof ValidationError) { | |
alert('参数错误') | |
} | |
if (e instanceof AuthenticationError) { | |
alert('请登录') | |
} | |
if (e instanceof RoleError) { | |
alert('管理员才能操作') | |
} | |
alert('未知错误,请重试') | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { superjson } from '@midwayjs/hooks' | |
export class ValidationError extends Error { | |
constructor (message) { | |
super(message) | |
} | |
} | |
superjson.registerClass(ValidationError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment