Skip to content

Commit

Permalink
feat: handle stream error (#6653)
Browse files Browse the repository at this point in the history
  • Loading branch information
darkskygit committed Apr 23, 2024
1 parent 01a0f60 commit 64ad83f
Showing 1 changed file with 45 additions and 3 deletions.
48 changes: 45 additions & 3 deletions packages/backend/server/src/plugins/copilot/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
BadRequestException,
Controller,
Get,
HttpException,
InternalServerErrorException,
Logger,
NotFoundException,
Expand All @@ -13,6 +14,7 @@ import {
} from '@nestjs/common';
import type { Request, Response } from 'express';
import {
catchError,
concatMap,
connect,
EMPTY,
Expand All @@ -21,6 +23,7 @@ import {
merge,
mergeMap,
Observable,
of,
switchMap,
toArray,
} from 'rxjs';
Expand All @@ -34,7 +37,7 @@ import { CopilotStorage } from './storage';
import { CopilotCapability } from './types';

export interface ChatEvent {
type: 'attachment' | 'message';
type: 'attachment' | 'message' | 'error';
id?: string;
data: string;
}
Expand Down Expand Up @@ -83,6 +86,19 @@ export class CopilotController {
return controller.signal;
}

private handleError(err: any) {
if (err instanceof Error) {
const ret = {
message: err.message,
status: (err as any).status,
};
if (err instanceof HttpException) {
ret.status = err.getStatus();
}
}
return err;
}

@Get('/chat/:sessionId')
async chat(
@CurrentUser() user: CurrentUser,
Expand Down Expand Up @@ -138,7 +154,14 @@ export class CopilotController {
@Query('messageId') messageId: string,
@Query() params: Record<string, string>
): Promise<Observable<ChatEvent>> {
await this.chatSession.checkQuota(user.id);
try {
await this.chatSession.checkQuota(user.id);
} catch (err) {
return of({
type: 'error' as const,
data: this.handleError(err),
});
}

const model = await this.chatSession.get(sessionId).then(s => s?.model);
const provider = this.provider.getProviderByCapability(
Expand Down Expand Up @@ -178,6 +201,12 @@ export class CopilotController {
switchMap(() => EMPTY)
)
)
),
catchError(err =>
of({
type: 'error' as const,
data: this.handleError(err),
})
)
);
}
Expand All @@ -190,7 +219,14 @@ export class CopilotController {
@Query('messageId') messageId: string,
@Query() params: Record<string, string>
): Promise<Observable<ChatEvent>> {
await this.chatSession.checkQuota(user.id);
try {
await this.chatSession.checkQuota(user.id);
} catch (err) {
return of({
type: 'error' as const,
data: this.handleError(err),
});
}

const hasAttachment = await this.hasAttachment(sessionId, messageId);
const model = await this.chatSession.get(sessionId).then(s => s?.model);
Expand Down Expand Up @@ -245,6 +281,12 @@ export class CopilotController {
switchMap(() => EMPTY)
)
)
),
catchError(err =>
of({
type: 'error' as const,
data: this.handleError(err),
})
)
);
}
Expand Down

0 comments on commit 64ad83f

Please sign in to comment.