-
Notifications
You must be signed in to change notification settings - Fork 121
/
ErrorResponseWriter.ts
31 lines (28 loc) · 1.23 KB
/
ErrorResponseWriter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { getLoggerFor } from '../../logging/LogUtil';
import type { HttpResponse } from '../../server/HttpResponse';
import { HttpError } from '../../util/errors/HttpError';
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
import type { ResponseDescription } from './response/ResponseDescription';
import { ResponseWriter } from './ResponseWriter';
/**
* Writes to an {@link HttpResponse} based on the incoming Error.
*/
export class ErrorResponseWriter extends ResponseWriter {
protected readonly logger = getLoggerFor(this);
public async canHandle(input: { response: HttpResponse; result: ResponseDescription | Error }): Promise<void> {
if (!(input.result instanceof Error)) {
throw new NotImplementedHttpError('Only errors are supported');
}
}
public async handle(input: { response: HttpResponse; result: Error }): Promise<void> {
let code = 500;
if (input.result instanceof HttpError) {
code = input.result.statusCode;
}
input.response.setHeader('content-type', 'text/plain');
input.response.writeHead(code);
input.response.end(typeof input.result.stack === 'string' ?
`${input.result.stack}\n` :
`${input.result.name}: ${input.result.message}\n`);
}
}