Make custom errors by extending Error (#69966)

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
This commit is contained in:
John Schulz 2020-06-29 17:08:50 -04:00 committed by GitHub
parent d9fcc585cf
commit 7db95a1691
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 21 deletions

View file

@ -4,26 +4,20 @@
* you may not use this file except in compliance with the Elastic License.
*/
/* eslint-disable max-classes-per-file */
export class IngestManagerError extends Error {
public type: IngestManagerErrorType;
public message: string;
constructor(type: IngestManagerErrorType, message: string) {
constructor(message?: string) {
super(message);
this.type = type;
this.message = message;
this.name = this.constructor.name; // for stack traces
}
}
export const getHTTPResponseCode = (error: IngestManagerError): number => {
switch (error.type) {
case IngestManagerErrorType.RegistryError:
return 502; // Bad Gateway
default:
return 400; // Bad Request
if (error instanceof RegistryError) {
return 502; // Bad Gateway
} else {
return 400; // Bad Request
}
};
export enum IngestManagerErrorType {
RegistryError,
}
export class RegistryError extends IngestManagerError {}

View file

@ -6,7 +6,7 @@
import fetch, { Response } from 'node-fetch';
import { streamToString } from './streams';
import { IngestManagerError, IngestManagerErrorType } from '../../../errors';
import { RegistryError } from '../../../errors';
export async function getResponse(url: string): Promise<Response> {
try {
@ -14,16 +14,12 @@ export async function getResponse(url: string): Promise<Response> {
if (response.ok) {
return response;
} else {
throw new IngestManagerError(
IngestManagerErrorType.RegistryError,
throw new RegistryError(
`Error connecting to package registry at ${url}: ${response.statusText}`
);
}
} catch (e) {
throw new IngestManagerError(
IngestManagerErrorType.RegistryError,
`Error connecting to package registry at ${url}: ${e.message}`
);
throw new RegistryError(`Error connecting to package registry at ${url}: ${e.message}`);
}
}