Fixed handling of server error messages in apiclient

This commit is contained in:
Philipp Czora
2018-11-14 21:34:10 +01:00
parent aff376f873
commit e1a0a367b4
4 changed files with 106 additions and 15 deletions

View File

@@ -1,5 +1,5 @@
// @flow
import { contextPath } from "./urls";
import {contextPath} from "./urls";
export const NOT_FOUND_ERROR = Error("not found");
export const UNAUTHORIZED_ERROR = Error("unauthorized");
@@ -11,15 +11,34 @@ const fetchOptions: RequestOptions = {
}
};
// TODO: dedup
function handleStatusCode(response: Response) {
if (!response.ok) {
if (response.status === 401) {
throw UNAUTHORIZED_ERROR;
return response.json().then(
json => {
throw Error(json.message);
},
() => {
throw UNAUTHORIZED_ERROR;
}
);
}
if (response.status === 404) {
throw NOT_FOUND_ERROR;
return response.json().then(
json => {
throw Error(json.message);
},
() => {
throw NOT_FOUND_ERROR;
}
);
}
throw new Error("server returned status code " + response.status);
return response.json().then(json => {
throw Error(json.message);
}, () => {
throw new Error("server returned status code " + response.status);
});
}
return response;
}

View File

@@ -1,15 +1,65 @@
// @flow
import { createUrl } from "./apiclient";
import {apiClient, createUrl} from "./apiclient";
import fetchMock from "fetch-mock";
describe("create url", () => {
it("should not change absolute urls", () => {
expect(createUrl("https://www.scm-manager.org")).toBe(
"https://www.scm-manager.org"
);
describe("apiClient", () => {
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
});
it("should add prefix for api", () => {
expect(createUrl("/users")).toBe("/api/v2/users");
expect(createUrl("users")).toBe("/api/v2/users");
describe("create url", () => {
it("should not change absolute urls", () => {
expect(createUrl("https://www.scm-manager.org")).toBe(
"https://www.scm-manager.org"
);
});
it("should add prefix for api", () => {
expect(createUrl("/users")).toBe("/api/v2/users");
expect(createUrl("users")).toBe("/api/v2/users");
});
});
describe("error handling", () => {
const error = {
message: "Error!!"
};
it("should append default error message for 401 if none provided", () => {
fetchMock.mock("api/v2/foo", 401);
return apiClient
.get("foo")
.catch(err => {
expect(err.message).toEqual("unauthorized");
});
});
it("should append error message for 401 if provided", () => {
fetchMock.mock("api/v2/foo", {"status": 401, body: error});
return apiClient
.get("foo")
.catch(err => {
expect(err.message).toEqual("Error!!");
});
});
it("should append default error message for 401 if none provided", () => {
fetchMock.mock("api/v2/foo", 404);
return apiClient
.get("foo")
.catch(err => {
expect(err.message).toEqual("not found");
});
});
it("should append error message for 404 if provided", () => {
fetchMock.mock("api/v2/foo", {"status": 404, body: error});
return apiClient
.get("foo")
.catch(err => {
expect(err.message).toEqual("Error!!");
});
});
});
});