gpt4 book ai didi

javascript - 如何使用异步将错误传递回调用者函数?

转载 作者:行者123 更新时间:2023-12-03 00:47:19 26 4
gpt4 key购买 nike

现在,如果找不到刚刚将空对象发送回客户端的“dateofBirth”,我将抛出错误,我如何将错误对象而不是空对象传递回客户端。基本上想发送回处理捕获

main.ts

export class GetSpecialtyQuestionsController extends Controller {
public static async process(@Request() request: ExpressRequest,
response: ExpressResponse): Promise < any > {
try {
const instance = new GetSpecialtyQuestionsController();
const data = await instance.execute(request);
response.status(200);
response.send(data);
} catch (err) {
response.status(200);
response.send(err.message);
}

}

// private _request: IRequestURL[] = [];

constructor() {
super();
}

private async execute(@Request() request: ExpressRequest): Promise < any > {
// const specialtyMembers = this.getSpecialtyMemberInfoFakeObject();
const specialtyMembers = await new SpecialtyCacheUtility().getSpecialtyMemberInfoCache(
request.body.getSpecialtyQuestionsRequest.header.serviceContext.tokenID);
if (!specialtyMembers) {
return this.errorHandler(request);
}
let proxyMember: ISpecialtyInfoObj = {}
as ISpecialtyInfoObj;
for (const member of specialtyMembers) {
if (member.specialtyIdEnc === request.body.getSpecialtyQuestionsRequest.details.specialtyIdEnc) {
proxyMember = member;
if (!member.dateOfBirth) {
throw new Error('no patient info for given HBS ID');
}
break;
}
}

}

最佳答案

创建自定义异常对象以在抛出错误时传递数据

class CustomError extends Error {
constructor(foo = 'bar', ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params);

// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}

// Custom debugging information
this.foo = foo;
this.date = new Date();
}
}

try {
throw new CustomError('baz', 'bazMessage');
} catch(e){
console.log(e.foo); //baz
console.log(e.message); //bazMessage
console.log(e.stack); //stacktrace
}

作为引用,请阅读官方 mdn 文档 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

关于javascript - 如何使用异步将错误传递回调用者函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com