@@ -7,24 +7,53 @@ export const NOT_FOUND_ERROR = 'NotFoundError';
7
7
export const APPLICATION_ERROR = 'ApplicationError' ;
8
8
export const SERVER_ERROR = 'ServerError' ;
9
9
10
+ export const COMMONS_NAMESPACE = 'https://www.lfenergy.org/compas/commons/v1' ;
11
+
10
12
export function getOpenScdElement ( ) : OpenSCD {
11
13
return < OpenSCD > document . querySelector ( 'open-scd' ) ;
12
14
}
13
15
14
- export function handleResponse ( response : Response ) : Promise < string > {
16
+ export async function handleResponse ( response : Response ) : Promise < string > {
15
17
if ( ! response . ok ) {
16
18
let type = APPLICATION_ERROR ;
17
19
if ( response . status === 404 ) {
18
20
type = NOT_FOUND_ERROR ;
19
- } else if ( response . status >= 500 )
20
- {
21
+ } else if ( response . status >= 500 ) {
21
22
type = SERVER_ERROR ;
22
23
}
23
- return Promise . reject ( { type : type , status : response . status , message : response . statusText } ) ;
24
+ return Promise . reject ( { type : type , status : response . status , message : await processErrorMessage ( response ) } ) ;
24
25
}
25
26
return Promise . resolve ( response . text ( ) ) ;
26
27
}
27
28
29
+ export async function processErrorMessage ( response : Response ) : Promise < string > {
30
+ // default we will return the status text from the response.
31
+ let errorMessage = response . statusText ;
32
+
33
+ const body = await response . text ( ) ;
34
+ const doc = await parseXml ( body ) ;
35
+ const messages = Array . from ( doc . querySelectorAll ( 'ErrorResponse > ErrorMessage' ) ?? [ ] ) ;
36
+ // But if there are messages found in the body, we will process these and replace the status text with that.
37
+ if ( messages . length > 0 ) {
38
+ errorMessage = '' ;
39
+ messages . forEach ( ( errorMessageElement , index ) => {
40
+ const code = errorMessageElement . getElementsByTagNameNS ( COMMONS_NAMESPACE , "Code" ) ! . item ( 0 ) ! . textContent ;
41
+ const message = errorMessageElement . getElementsByTagNameNS ( COMMONS_NAMESPACE , "Message" ) ! . item ( 0 ) ! . textContent ;
42
+
43
+ if ( index > 0 ) {
44
+ errorMessage += ', ' ;
45
+ }
46
+
47
+ errorMessage += message ;
48
+ if ( code ) {
49
+ errorMessage += ' (' + code + ')' ;
50
+ }
51
+ } )
52
+ }
53
+
54
+ return errorMessage ;
55
+ }
56
+
28
57
export function parseXml ( textContent : string ) : Promise < Document > {
29
58
return Promise . resolve ( new DOMParser ( ) . parseFromString ( textContent , 'application/xml' ) ) ;
30
59
}
0 commit comments