From 5b8e3b41898f9b0506e16fa4b3d415ffdbbe1560 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Mon, 29 Mar 2021 18:18:25 +0200 Subject: [PATCH] web: improve error handling Signed-off-by: Jens Langhammer --- web/src/elements/forms/Form.ts | 18 ++++++++---------- web/src/utils.ts | 5 +++++ 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/web/src/elements/forms/Form.ts b/web/src/elements/forms/Form.ts index 56b63c581..d4e267aed 100644 --- a/web/src/elements/forms/Form.ts +++ b/web/src/elements/forms/Form.ts @@ -11,14 +11,12 @@ import PFForm from "@patternfly/patternfly/components/Form/form.css"; import PFFormControl from "@patternfly/patternfly/components/FormControl/form-control.css"; import { MessageLevel } from "../messages/Message"; import { IronFormElement } from "@polymer/iron-form/iron-form"; - -interface ErrorResponse { - [key: string]: string[]; -} +import { camelToSnake } from "../../utils"; +import { ValidationError } from "authentik-api/src"; export class APIError extends Error { - constructor(public response: ErrorResponse) { + constructor(public response: ValidationError) { super(); } @@ -31,7 +29,7 @@ export class Form extends LitElement { successMessage = ""; @property() - send!: (data: T) => Promise; + send!: (data: T) => Promise; static get styles(): CSSResult[] { return [PFBase, PFCard, PFButton, PFForm, PFFormControl, AKGlobal, css` @@ -62,7 +60,7 @@ export class Form extends LitElement { return json as unknown as T; } - submit(ev: Event): Promise | undefined { + submit(ev: Event): Promise | undefined { ev.preventDefault(); const ironForm = this.shadowRoot?.querySelector("iron-form"); if (!ironForm) { @@ -78,7 +76,7 @@ export class Form extends LitElement { return r; }).catch((ex: Response) => { if (ex.status > 399 && ex.status < 500) { - return ex.json().then((errorMessage: ErrorResponse) => { + return ex.json().then((errorMessage: ValidationError) => { if (!errorMessage) return errorMessage; if (errorMessage instanceof Error) { throw errorMessage; @@ -87,8 +85,8 @@ export class Form extends LitElement { elements.forEach((element) => { const elementName = element.name; if (!elementName) return; - if (elementName in errorMessage) { - element.errorMessage = errorMessage[elementName].join(", "); + if (camelToSnake(elementName) in errorMessage) { + element.errorMessage = errorMessage[camelToSnake(elementName)].join(", "); element.invalid = true; } }); diff --git a/web/src/utils.ts b/web/src/utils.ts index 3e92cba4b..89c3e0eea 100644 --- a/web/src/utils.ts +++ b/web/src/utils.ts @@ -51,3 +51,8 @@ export function loading(v: T, actual: TemplateResult): TemplateResult { } return actual; } + +export function camelToSnake(key: string): string { + var result = key.replace(/([A-Z])/g, " $1"); + return result.split(' ').join('_').toLowerCase(); +}