diff --git a/spec/core/Client.ts b/spec/core/Client.ts index 55d98cc9e..4841c0402 100644 --- a/spec/core/Client.ts +++ b/spec/core/Client.ts @@ -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"; @@ -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", () => { diff --git a/spec/core/GraphClientError.ts b/spec/core/GraphClientError.ts new file mode 100644 index 000000000..b25569348 --- /dev/null +++ b/spec/core/GraphClientError.ts @@ -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); + }); +}); diff --git a/src/CustomAuthenticationProvider.ts b/src/CustomAuthenticationProvider.ts index 58b7eb9f1..eac4ba6e3 100644 --- a/src/CustomAuthenticationProvider.ts +++ b/src/CustomAuthenticationProvider.ts @@ -9,6 +9,7 @@ * @module CustomAuthenticationProvider */ +import { GraphClientError } from "./GraphClientError"; import { AuthenticationProvider } from "./IAuthenticationProvider"; import { AuthProvider } from "./IAuthProvider"; @@ -43,11 +44,18 @@ export class CustomAuthenticationProvider implements AuthenticationProvider { */ public async getAccessToken(): Promise { 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); } }); }); diff --git a/src/GraphClientError.ts b/src/GraphClientError.ts new file mode 100644 index 000000000..f6ef31a8d --- /dev/null +++ b/src/GraphClientError.ts @@ -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"}, ""); + * }); + */ + 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); + } +} diff --git a/src/GraphErrorHandler.ts b/src/GraphErrorHandler.ts index 310596968..3fe92be72 100644 --- a/src/GraphErrorHandler.ts +++ b/src/GraphErrorHandler.ts @@ -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 @@ -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 * @@ -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; } @@ -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 @@ -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); diff --git a/src/GraphRequest.ts b/src/GraphRequest.ts index 7ec736be1..050ed00c7 100644 --- a/src/GraphRequest.ts +++ b/src/GraphRequest.ts @@ -8,7 +8,7 @@ /** * @module GraphRequest */ - +import { GraphClientError } from "./GraphClientError"; import { GraphError } from "./GraphError"; import { GraphErrorHandler } from "./GraphErrorHandler"; import { oDataQueryNames, serializeContent, urlJoin } from "./GraphRequestUtil"; @@ -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);