@@ -14,13 +14,63 @@ export async function responseError(response) {
1414 * Used for example to handle the displaying of the error alert when using the ConfirmActionButton.
1515 */
1616export class AlertError extends Error {
17+ /** @type {null | { loc: string[], msg: string } } */
18+ simpleValidationMessage ;
19+
1720 /**
1821 * @param {any } reason
22+ * @param {number|null } statusCode
1923 */
20- constructor ( reason ) {
24+ constructor ( reason , statusCode = null ) {
2125 super ( ) ;
2226 this . reason = reason ;
27+ this . simpleValidationMessage = getSimpleValidationMessage ( reason , statusCode ) ;
28+ }
29+
30+ /**
31+ * @param {string[] } loc expected location of the validation message
32+ * @returns {string | null } the validation message, if found
33+ */
34+ getSimpleValidationMessage ( ...loc ) {
35+ if ( ! this . simpleValidationMessage ) {
36+ return null ;
37+ }
38+ if ( this . simpleValidationMessage . loc . length !== loc . length ) {
39+ return null ;
40+ }
41+ for ( let i = 0 ; i < loc . length ; i ++ ) {
42+ if ( this . simpleValidationMessage . loc [ i ] !== loc [ i ] ) {
43+ return null ;
44+ }
45+ }
46+ return this . simpleValidationMessage . msg ;
47+ }
48+ }
49+
50+ /**
51+ * Detects if the error message is a simple validation message for one field.
52+ *
53+ * @param {any } reason
54+ * @param {number | null } statusCode
55+ * @returns {null | { loc: string[], msg: string } }
56+ */
57+ function getSimpleValidationMessage ( reason , statusCode ) {
58+ if (
59+ statusCode !== 422 ||
60+ ! ( 'detail' in reason ) ||
61+ ! Array . isArray ( reason . detail ) ||
62+ reason . detail . length !== 1
63+ ) {
64+ return null ;
65+ }
66+ const err = reason . detail [ 0 ] ;
67+ if ( ! Array . isArray ( err . loc ) || ! err . msg || err . type !== 'value_error' ) {
68+ return null ;
2369 }
70+ return {
71+ loc : err . loc . length > 1 && err . loc [ 0 ] === 'body' ? err . loc . slice ( 1 ) : err . loc ,
72+ msg : err . msg
73+ } ;
2474}
2575
2676/**
0 commit comments