我编写了一个util函数,用于解析API异常并返回建模的TS类型.
interface NotFoundException {
type: 'notFound'
}
interface PermissionException {
type: 'permission'
}
interface BadRequestException {
type: 'badRequest'
}
// Example shape of API Error
interface APIError {
statusCode: number;
}
type KnownExceptions = NotFoundException | PermissionException | BadRequestException;
function exceptionHandler(err: unknown): KnownExceptions {
const statusCode = (err as APIError).statusCode ?? -1;
if (statusCode === 404) {
return {
type: 'notFound'
}
}
if (statusCode === 403) {
return {
type: 'permission'
}
}
if (statusCode === 400) {
return {
type: 'badRequest'
}
}
throw new Error('Unknown error', { cause: err });
}
有些API不会返回所有类型,因此我需要显式处理其他类型
interface APIInput {
prop: string;
}
interface APIOutput {
id: string;
}
function callAPI(input: APIInput): APIOutput | PermissionException | NotFoundException {
try {
//Mock API call
return {
id: 'id'
};
} catch (err: unknown) {
const e = exceptionHandler(err);
// Problem: This API (and others) cannot throw this/some exceptions
// Need a function that will restrict the types returned by exceptionHandler
// and throw 'Unexpected exception' for impossible cases
if (e.type === 'badRequest') {
throw new Error('Unexpected exception', { cause: err });
}
return e;
}
}
有没有一种方法可以让我写一个函数,将异常联合的返回类型限制为我想要的类型,并对所有其他类型抛出Unexpected exception
个错误?
由于TS不能将类型作为参数,我发现很难弄清楚这一点.