Skip to content

Commit

Permalink
Make custom errors by extending Error (#69966)
Browse files Browse the repository at this point in the history
Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
John Schulz and elasticmachine committed Jul 1, 2020
1 parent b1431e8 commit 5dcbb00
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 21 deletions.
22 changes: 8 additions & 14 deletions x-pack/plugins/ingest_manager/server/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,20 @@

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 {
const response = await fetch(url);
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}`);
}
}

Expand Down

0 comments on commit 5dcbb00

Please sign in to comment.