现在,如果未发现“ 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;
}
}
}
答案 0 :(得分:1)
创建自定义异常对象以在引发错误时传递数据
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