From 7a5f3b2dd468c3d555bc04c2649ff654efb006ea Mon Sep 17 00:00:00 2001 From: Tomi Belan Date: Thu, 12 Dec 2024 19:01:03 +0100 Subject: [PATCH] Fix reporting of server-side errors in "bw sync". (#6855) Co-authored-by: SmithThe4th --- apps/cli/src/models/response.ts | 35 ++++++++++++++++++------- apps/cli/src/vault/sync.command.ts | 4 ++- libs/common/src/services/api.service.ts | 1 - 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/apps/cli/src/models/response.ts b/apps/cli/src/models/response.ts index a0e03ae052..76d9509226 100644 --- a/apps/cli/src/models/response.ts +++ b/apps/cli/src/models/response.ts @@ -1,21 +1,36 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; + import { BaseResponse } from "./response/base.response"; +function getErrorMessage(error: unknown): string { + if (typeof error === "string") { + return error; + } + if (error instanceof ErrorResponse) { + const message = error.getSingleMessage(); + if (message) { + return message; + } + } + if (error instanceof Error) { + return String(error); + } + if (error) { + const errorWithMessage: { message?: unknown } = error; // To placate TypeScript. + if (errorWithMessage.message && typeof errorWithMessage.message === "string") { + return errorWithMessage.message; + } + } + return JSON.stringify(error); +} + export class Response { static error(error: any, data?: any): Response { const res = new Response(); res.success = false; - if (typeof error === "string") { - res.message = error; - } else { - res.message = - error.message != null - ? error.message - : error.toString() === "[object Object]" - ? JSON.stringify(error) - : error.toString(); - } + res.message = getErrorMessage(error); res.data = data; return res; } diff --git a/apps/cli/src/vault/sync.command.ts b/apps/cli/src/vault/sync.command.ts index 7a5032a097..ebf790c1c1 100644 --- a/apps/cli/src/vault/sync.command.ts +++ b/apps/cli/src/vault/sync.command.ts @@ -21,7 +21,9 @@ export class SyncCommand { const res = new MessageResponse("Syncing complete.", null); return Response.success(res); } catch (e) { - return Response.error("Syncing failed: " + e.toString()); + const response = Response.error(e); + response.message = "Syncing failed: " + response.message; + return response; } } diff --git a/libs/common/src/services/api.service.ts b/libs/common/src/services/api.service.ts index ad40466034..dc0a8d61f6 100644 --- a/libs/common/src/services/api.service.ts +++ b/libs/common/src/services/api.service.ts @@ -1948,7 +1948,6 @@ export class ApiService implements ApiServiceAbstraction { responseJson.error === "invalid_grant") ) { await this.logoutCallback("invalidGrantError"); - return null; } }