Skip to content

Instantly share code, notes, and snippets.

@Lxxyx
Last active March 18, 2021 03:46
Show Gist options
  • Save Lxxyx/f7e35c0ff09fac32b642f64b8e000538 to your computer and use it in GitHub Desktop.
Save Lxxyx/f7e35c0ff09fac32b642f64b8e000538 to your computer and use it in GitHub Desktop.
错误处理
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')
}
}
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('未知错误,请重试')
}
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