diff --git a/scm-ui-components/packages/ui-components/src/apiclient.js b/scm-ui-components/packages/ui-components/src/apiclient.js index 0d52167d95..ce7de1b757 100644 --- a/scm-ui-components/packages/ui-components/src/apiclient.js +++ b/scm-ui-components/packages/ui-components/src/apiclient.js @@ -1,6 +1,6 @@ // @flow import { contextPath } from "./urls"; -import { createBackendError } from "./errors"; +import {createBackendError, isBackendError, UnauthorizedError} from "./errors"; import type { BackendErrorContent } from "./errors"; const fetchOptions: RequestOptions = { @@ -10,9 +10,7 @@ const fetchOptions: RequestOptions = { } }; -function isBackendError(response) { - return response.headers.get("Content-Type") === "application/vnd.scmm-error+json;v=2"; -} + function handleFailure(response: Response) { if (!response.ok) { @@ -22,6 +20,9 @@ function handleFailure(response: Response) { throw createBackendError(content, response.status); }); } else { + if (response.status === 401) { + throw new UnauthorizedError("Unauthorized", 401); + } throw new Error("server returned status code " + response.status); } } diff --git a/scm-ui-components/packages/ui-components/src/errors.js b/scm-ui-components/packages/ui-components/src/errors.js index 420f8d6fad..9b278c7ddd 100644 --- a/scm-ui-components/packages/ui-components/src/errors.js +++ b/scm-ui-components/packages/ui-components/src/errors.js @@ -1,5 +1,5 @@ // @flow -type Context = {type: string, id: string}[]; +type Context = { type: string, id: string }[]; export type BackendErrorContent = { transactionId: string, @@ -10,7 +10,6 @@ export type BackendErrorContent = { }; export class BackendError extends Error { - transactionId: string; errorCode: string; url: ?string; @@ -26,12 +25,13 @@ export class BackendError extends Error { this.context = content.context; this.statusCode = statusCode; } - } -export class UnauthorizedError extends BackendError { - constructor(content: BackendErrorContent, statusCode: number) { - super(content, "UnauthorizedError", statusCode); +export class UnauthorizedError extends Error { + statusCode: number; + constructor(message: string, statusCode: number) { + super(message); + this.statusCode = statusCode; } } @@ -40,14 +40,18 @@ export class NotFoundError extends BackendError { super(content, "NotFoundError", statusCode); } } - -export function createBackendError(content: BackendErrorContent, statusCode: number) { +export function createBackendError( + content: BackendErrorContent, + statusCode: number +) { switch (statusCode) { - case 401: - return new UnauthorizedError(content, statusCode); case 404: return new NotFoundError(content, statusCode); default: return new BackendError(content, "BackendError", statusCode); } } + +export function isBackendError(response: Response) { + return response.headers.get("Content-Type") === "application/vnd.scmm-error+json;v=2"; +}