Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions spec/core/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import "isomorphic-fetch";

import { CustomAuthenticationProvider, TelemetryHandler } from "../../src";
import { Client } from "../../src/Client";
import { GraphClientError } from "../../src/GraphClientError";
import { AuthProvider } from "../../src/IAuthProvider";
import { ClientOptions } from "../../src/IClientOptions";
import { Options } from "../../src/IOptions";
Expand Down Expand Up @@ -101,6 +102,48 @@ describe("Client.ts", () => {
const response = await client.api("me").get();
assert.equal(response, responseBody);
});

it("Should throw error in case the access token is undefined", async () => {
try {
const options = {
defaultVersion: "v1.0",
debugLogging: true,
authProvider: (done) => {
done(null, getTokenFunction());
},
};

const getTokenFunction = (): string => {
return undefined;
};
const client = Client.init(options);
const res = await client.api("/test").get();
} catch (error) {
assert.isTrue(error instanceof GraphClientError);
assert.isDefined(error.message);
}
});

it("Should throw error in case the access token is empty", async () => {
const customError = { message: "Token is empty" };
try {
const options = {
defaultVersion: "v1.0",
debugLogging: true,
authProvider: (done) => {
done(customError, getTokenFunction());
},
};
const getTokenFunction = (): string => {
return "";
};
const client = Client.init(options);
const res = await client.api("/test").get();
} catch (error) {
assert.isTrue(error instanceof GraphClientError);
assert.equal(error.customError, customError);
}
});
});

describe("init", () => {
Expand Down
34 changes: 34 additions & 0 deletions spec/core/GraphClientError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/

import { assert } from "chai";

import { GraphClientError } from "../../src/GraphClientError";

describe("GraphClientError", () => {
const message = "test";
const name = "test_name";
it("Should return GraphClientError error with message set", () => {
const gError = new GraphClientError(message);
assert.equal(gError.message, message);
});

it("Should return GraphClientError when Error object is passed", () => {
const errorParameter = new Error(message);
errorParameter.name = name;
const gError = GraphClientError.setGraphClientError(errorParameter);
assert.equal(gError.message, message);
assert.equal(gError.name, name);
});

it("Should return GraphClientError when custom error object is passed", () => {
const customErrorParameter = { errorName: name, errorMessage: message };
const gError = GraphClientError.setGraphClientError(customErrorParameter);
assert.isDefined(gError.customError);
assert.equal(gError.customError, customErrorParameter);
});
});
12 changes: 10 additions & 2 deletions src/CustomAuthenticationProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* @module CustomAuthenticationProvider
*/

import { GraphClientError } from "./GraphClientError";
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { AuthProvider } from "./IAuthProvider";

Expand Down Expand Up @@ -43,11 +44,18 @@ export class CustomAuthenticationProvider implements AuthenticationProvider {
*/
public async getAccessToken(): Promise<any> {
return new Promise((resolve: (accessToken: string) => void, reject: (error: any) => void) => {
this.provider((error: any, accessToken: string | null) => {
this.provider(async (error: any, accessToken: string | null) => {
if (accessToken) {
resolve(accessToken);
} else {
reject(error);
if (!error) {
const invalidTokenMessage = "Access token is undefined or empty.\
Please provide a valid token.\
For more help - https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md";
error = new GraphClientError(invalidTokenMessage);
}
const err = await GraphClientError.setGraphClientError(error);
reject(err);
}
});
});
Expand Down
61 changes: 61 additions & 0 deletions src/GraphClientError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/

/**
* @module GraphClientError
*/

/**
* @class
* Create GraphClientError object to handle client-side errors
* encountered within the JavaScript Client SDK.
* Whereas GraphError Class should be used to handle errors in the response from the Graph API.
*/

export class GraphClientError extends Error {
/**
* @public
* A custom error. This property should set be when the error is not of instanceOf Error/GraphClientError.
* Example =
* const client = MicrosoftGraph.Client.init({
* defaultVersion: "v1.0",
* authProvider: (done) => { done({TokenError:"AccessToken cannot be null"}, "<ACCESS_TOKEN>");
* });
*/
public customError?: any;

/**
* @public
* @static
* @async
* To set the GraphClientError object
* @param {any} - The error returned encountered by the Graph JavaScript Client SDK while processing request
* @returns GraphClientError object set to the error passed
*/
public static setGraphClientError(error: any): GraphClientError {
let graphClientError: GraphClientError;
if (error instanceof Error) {
graphClientError = error;
} else {
graphClientError = new GraphClientError();
graphClientError.customError = error;
}
return graphClientError;
}

/**
* @public
* @constructor
* Creates an instance of GraphClientError
* @param {string} message? - Error message
* @returns An instance of GraphClientError
*/
public constructor(message?: string) {
super(message);
Object.setPrototypeOf(this, GraphClientError.prototype);
}
}
32 changes: 23 additions & 9 deletions src/GraphErrorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@
import { GraphError } from "./GraphError";
import { GraphRequestCallback } from "./IGraphRequestCallback";

/**
* @interface
* Signature for the json represent of the error response from the Graph API
* https://docs.microsoft.com/en-us/graph/errors
* @property {[key: string] : string | number} - The Key value pair
*/
interface GraphAPIErrorResponse {
error: {
code: string;
message: string;
innerError: any;
};
}

/**
* @class
* Class for GraphErrorHandler
Expand Down Expand Up @@ -41,7 +55,7 @@ export class GraphErrorHandler {
* @static
* @async
* Populates the GraphError instance from the Error returned by graph service
* @param {any} error - The error returned by graph service or some native error
* @param {GraphAPIErrorResponse} graphError - The error possibly returned by graph service or some native error
* @param {number} statusCode - The status code of the response
* @returns A promise that resolves to GraphError instance
*
Expand All @@ -57,19 +71,17 @@ export class GraphErrorHandler {
* }
* }
*/
private static constructErrorFromResponse(error: any, statusCode: number): GraphError {
error = error.error;
private static constructErrorFromResponse(graphError: GraphAPIErrorResponse, statusCode: number): GraphError {
const error = graphError.error;
const gError = new GraphError(statusCode, error.message);
gError.code = error.code;
if (error.innerError !== undefined) {
gError.requestId = error.innerError["request-id"];
gError.date = new Date(error.innerError.date);
}
try {
gError.body = JSON.stringify(error);
} catch (error) {
// tslint:disable-line: no-empty
}

gError.body = JSON.stringify(error);

return gError;
}

Expand All @@ -78,6 +90,7 @@ export class GraphErrorHandler {
* @static
* @async
* To get the GraphError object
* Reference - https://docs.microsoft.com/en-us/graph/errors
* @param {any} [error = null] - The error returned by graph service or some native error
* @param {number} [statusCode = -1] - The status code of the response
* @param {GraphRequestCallback} [callback] - The graph request callback function
Expand All @@ -87,10 +100,11 @@ export class GraphErrorHandler {
let gError: GraphError;
if (error && error.error) {
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode);
} else if (typeof Error !== "undefined" && error instanceof Error) {
} else if (error instanceof Error) {
gError = GraphErrorHandler.constructError(error, statusCode);
} else {
gError = new GraphError(statusCode);
gError.body = error; // if a custom error is passed which is not instance of Error object or a graph API response
}
if (typeof callback === "function") {
callback(gError, null);
Expand Down
8 changes: 6 additions & 2 deletions src/GraphRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
/**
* @module GraphRequest
*/

import { GraphClientError } from "./GraphClientError";
import { GraphError } from "./GraphError";
import { GraphErrorHandler } from "./GraphErrorHandler";
import { oDataQueryNames, serializeContent, urlJoin } from "./GraphRequestUtil";
Expand Down Expand Up @@ -379,8 +379,12 @@ export class GraphRequest {
const response: any = await GraphResponseHandler.getResponse(rawResponse, this._responseType, callback);
return response;
} catch (error) {
if (error instanceof GraphClientError) {
throw error;
}
let statusCode: number;
if (typeof rawResponse !== "undefined") {

if (rawResponse) {
statusCode = rawResponse.status;
}
const gError: GraphError = await GraphErrorHandler.getError(error, statusCode, callback);
Expand Down