Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Throw an actual error object in the HalResource service

Oliver Günther22d5e22a5be0
diff --git a/frontend/src/app/core/apiv3/endpoints/work_packages/api-v3-work-packages-paths.ts b/frontend/src/app/core/apiv3/endpoints/work_packages/api-v3-work-packages-paths.ts
index f00f8a7214a..fd8a68c69fb 100644
--- a/frontend/src/app/core/apiv3/endpoints/work_packages/api-v3-work-packages-paths.ts
+++ b/frontend/src/app/core/apiv3/endpoints/work_packages/api-v3-work-packages-paths.ts
@@ -157,7 +157,7 @@ export class APIV3WorkPackagesPaths extends CachableAPIV3Collection<WorkPackageR
protected loadCollectionsFor(ids:string[]):Promise<WorkPackageCollectionResource[]> {
return this
.halResourceService
- .getAllPaginated<WorkPackageCollectionResource[]>(
+ .getAllPaginated<WorkPackageCollectionResource>(
this.path,
ids.length,
{
diff --git a/frontend/src/app/features/hal/services/hal-aware-error-handler.ts b/frontend/src/app/features/hal/services/hal-aware-error-handler.ts
index a9be0766281..2bc6cefffdc 100644
--- a/frontend/src/app/features/hal/services/hal-aware-error-handler.ts
+++ b/frontend/src/app/features/hal/services/hal-aware-error-handler.ts
@@ -2,6 +2,7 @@ import { ErrorHandler, Injectable } from '@angular/core';
import { I18nService } from 'core-app/core/i18n/i18n.service';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
+import { HalError } from 'core-app/features/hal/services/hal-error';
@Injectable()
export class HalAwareErrorHandler extends ErrorHandler {
@@ -13,10 +14,13 @@ export class HalAwareErrorHandler extends ErrorHandler {
super();
}
- public handleError(error:unknown) {
+ public handleError(error:unknown):void {
let message:string = this.text.internal_error;
- if (error instanceof ErrorResource) {
+ if (error instanceof HalError) {
+ console.error('Returned HTTP HAL error resource %O', error.message);
+ message += ` ${error.message}`;
+ } else if (error instanceof ErrorResource) {
console.error('Returned error resource %O', error);
message += ` ${error.errorMessages.join('\n')}`;
} else if (error instanceof HalResource) {
diff --git a/frontend/src/app/features/hal/services/hal-error.ts b/frontend/src/app/features/hal/services/hal-error.ts
new file mode 100644
index 00000000000..d77141a31d7
--- /dev/null
+++ b/frontend/src/app/features/hal/services/hal-error.ts
@@ -0,0 +1,20 @@
+import { HttpErrorResponse } from '@angular/common/http';
+import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
+
+export class HalError implements Error {
+ readonly name = 'HALError';
+
+ get message():string {
+ return this.resource.message || this.httpError?.message || 'Unknown error';
+ }
+
+ get errorIdentifier():string {
+ return this.resource.errorIdentifier;
+ }
+
+ constructor(
+ readonly httpError:HttpErrorResponse,
+ readonly resource:ErrorResource,
+ ) {
+ }
+}
diff --git a/frontend/src/app/features/hal/services/hal-resource-notification.service.ts b/frontend/src/app/features/hal/services/hal-resource-notification.service.ts
index e98b0802be1..31f09250d62 100644
--- a/frontend/src/app/features/hal/services/hal-resource-notification.service.ts
+++ b/frontend/src/app/features/hal/services/hal-resource-notification.service.ts
@@ -37,6 +37,7 @@ import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { InjectField } from 'core-app/shared/helpers/angular/inject-field.decorator';
import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
+import { HalError } from 'core-app/features/hal/services/hal-error';
@Injectable()
export class HalResourceNotificationService {
@@ -78,8 +79,8 @@ export class HalResourceNotificationService {
// Some transformation may already have returned the error as a HAL resource,
// which we will forward to handleErrorResponse
- if (response instanceof ErrorResource) {
- return this.handleErrorResponse(response, resource);
+ if (response instanceof HalError) {
+ return this.handleErrorResponse(response.resource, resource);
}
const errorBody = this.retrieveError(response);
@@ -108,7 +109,7 @@ export class HalResourceNotificationService {
public retrieveErrorMessage(response:unknown):string {
const error = this.retrieveError(response);
- if (error instanceof ErrorResource) {
+ if (error instanceof ErrorResource || error instanceof HalError) {
return error.message;
}
@@ -142,6 +143,10 @@ export class HalResourceNotificationService {
}
protected handleErrorResponse(errorResource:any, resource?:HalResource) {
+ if (errorResource instanceof HalError && resource) {
+ return this.showError(errorResource.resource, resource);
+ }
+
if (!(errorResource instanceof ErrorResource)) {
return this.showGeneralError(errorResource);
}
@@ -150,7 +155,7 @@ export class HalResourceNotificationService {
return this.showError(errorResource, resource);
}
- this.showApiErrorMessages(errorResource);
+ return this.showApiErrorMessages(errorResource);
}
public showError(errorResource:any, resource:HalResource) {
diff --git a/frontend/src/app/features/hal/services/hal-resource.service.ts b/frontend/src/app/features/hal/services/hal-resource.service.ts
index cbcf49d360e..919f1ff7d55 100644
--- a/frontend/src/app/features/hal/services/hal-resource.service.ts
+++ b/frontend/src/app/features/hal/services/hal-resource.service.ts
@@ -26,10 +26,23 @@
// See docs/COPYRIGHT.rdoc for more details.
//++
-import { Injectable, Injector } from '@angular/core';
-import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
-import { catchError, map } from 'rxjs/operators';
-import { Observable, throwError } from 'rxjs';
+import {
+ Injectable,
+ Injector,
+} from '@angular/core';
+import {
+ HttpClient,
+ HttpErrorResponse,
+ HttpParams,
+} from '@angular/common/http';
+import {
+ catchError,
+ map,
+} from 'rxjs/operators';
+import {
+ Observable,
+ throwError,
+} from 'rxjs';
import { CollectionResource } from 'core-app/features/hal/resources/collection-resource';
import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
import * as Pako from 'pako';
@@ -41,10 +54,17 @@ import {
HTTPClientParamMap,
HTTPSupportedMethods,
} from 'core-app/features/hal/http/http.interfaces';
-import { HalLink, HalLinkInterface } from 'core-app/features/hal/hal-link/hal-link';
+import {
+ HalLink,
+ HalLinkInterface,
+} from 'core-app/features/hal/hal-link/hal-link';
import { URLParamsEncoder } from 'core-app/features/hal/services/url-params-encoder';
-import { HalResource, HalResourceClass } from 'core-app/features/hal/resources/hal-resource';
+import {
+ HalResource,
+ HalResourceClass,
+} from 'core-app/features/hal/resources/hal-resource';
import { initializeHalProperties } from '../helpers/hal-resource-builder';
+import { HalError } from 'core-app/features/hal/services/hal-error';
export interface HalResourceFactoryConfigInterface {
cls?:any;
@@ -58,18 +78,20 @@ export class HalResourceService {
*/
private config:{ [typeName:string]:HalResourceFactoryConfigInterface } = {};
- constructor(readonly injector:Injector,
- readonly http:HttpClient) {
+ constructor(
+ readonly injector:Injector,
+ readonly http:HttpClient,
+ ) {
}
/**
* Perform a HTTP request and return a HalResource promise.
*/
- public request<T extends HalResource>(method:HTTPSupportedMethods, href:string, data?:any, headers:HTTPClientHeaders = {}):Observable<T> {
+ public request<T extends HalResource>(method:HTTPSupportedMethods, href:string, data?:unknown, headers:HTTPClientHeaders = {}):Observable<T> {
// HttpClient requires us to create HttpParams instead of passing data for get
// so forward to that method instead.
if (method === 'get') {
- return this.get(href, data, headers);
+ return this.get(href, data as HTTPClientParamMap|undefined, headers);
}
const config:HTTPClientOptions = {
@@ -79,20 +101,19 @@ export class HalResourceService {
responseType: 'json',
};
- return this._request(method, href, config);
+ return this.performRequest(method, href, config);
}
- private _request<T>(method:HTTPSupportedMethods, href:string, config:HTTPClientOptions):Observable<T> {
- return this.http.request<T>(method, href, config)
+ private performRequest<T extends HalResource>(method:HTTPSupportedMethods, href:string, config:HTTPClientOptions):Observable<T> {
+ return this.http.request(method, href, config)
.pipe(
- map((response:any) => this.createHalResource(response)),
+ map((response:unknown) => this.createHalResource<T>(response)),
catchError((error:HttpErrorResponse) => {
whenDebugging(() => console.error(`Failed to ${method} ${href}: ${error.name}`));
const resource = this.createHalResource<ErrorResource>(error.error);
- resource.httpError = error;
- return throwError(resource);
+ return throwError(new HalError(error, resource));
}),
- ) as any;
+ );
}
/**
@@ -111,7 +132,7 @@ export class HalResourceService {
responseType: 'json',
};
- return this._request('get', href, config);
+ return this.performRequest('get', href, config);
}
/**
@@ -124,20 +145,27 @@ export class HalResourceService {
* @param headers
* @return {Promise<CollectionResource[]>}
*/
- public async getAllPaginated<T extends HalResource[]>(href:string, expected:number, params:any = {}, headers:HTTPClientHeaders = {}) {
+ public async getAllPaginated<T extends CollectionResource>(
+ href:string,
+ expected:number,
+ params:Record<string, string|number> = {},
+ headers:HTTPClientHeaders = {},
+ ):Promise<T[]> {
// Total number retrieved
let retrieved = 0;
// Current offset page
let page = 1;
// Accumulated results
- const allResults:T = [] as any;
+ const allResults:T[] = [];
// If possible, request all at once.
- params.pageSize = expected;
+ const requestParams = { ...params };
+ requestParams.pageSize = expected;
while (retrieved < expected) {
- params.offset = page;
+ requestParams.offset = page;
- const promise = this.request('get', href, this.toEprops(params), headers).toPromise();
+ const promise = this.request<T>('get', href, this.toEprops(requestParams), headers).toPromise();
+ // eslint-disable-next-line no-await-in-loop
const results = await promise;
if (results.count === 0) {
diff --git a/frontend/src/app/features/work-packages/components/work-package-comment/work-package-comment.component.ts b/frontend/src/app/features/work-packages/components/work-package-comment/work-package-comment.component.ts
index 9bc48c1fd4d..f53c2534efa 100644
--- a/frontend/src/app/features/work-packages/components/work-package-comment/work-package-comment.component.ts
+++ b/frontend/src/app/features/work-packages/components/work-package-comment/work-package-comment.component.ts
@@ -50,6 +50,7 @@ import { CommentService } from 'core-app/features/work-packages/components/wp-ac
import { WorkPackagesActivityService } from 'core-app/features/work-packages/components/wp-single-view-tabs/activity-panel/wp-activity.service';
import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
+import { HalError } from 'core-app/features/hal/services/hal-error';
@Component({
selector: 'work-package-comment',
@@ -146,13 +147,13 @@ export class WorkPackageCommentComponent extends WorkPackageCommentFieldHandler
this.inFlight = true;
await this.onSubmit();
const indicator = this.loadingIndicator.wpDetails;
- return indicator.promise = this.commentService.createComment(this.workPackage, this.commentValue)
+ indicator.promise = this.commentService.createComment(this.workPackage, this.commentValue)
.then(() => {
this.active = false;
this.NotificationsService.addSuccess(this.I18n.t('js.work_packages.comment_added'));
- this.wpLinkedActivities.require(this.workPackage, true);
- this
+ void this.wpLinkedActivities.require(this.workPackage, true);
+ void this
.apiV3Service
.work_packages
.id(this.workPackage.id!)
@@ -163,12 +164,14 @@ export class WorkPackageCommentComponent extends WorkPackageCommentFieldHandler
})
.catch((error:any) => {
this.inFlight = false;
- if (error instanceof ErrorResource) {
- this.workPackageNotificationService.showError(error, this.workPackage);
+ if (error instanceof HalError) {
+ this.workPackageNotificationService.showError(error.resource, this.workPackage);
} else {
this.NotificationsService.addError(this.I18n.t('js.work_packages.comment_send_failed'));
}
});
+
+ return indicator.promise;
}
scrollToBottom():void {
diff --git a/frontend/src/app/features/work-packages/components/wp-new/wp-create.component.ts b/frontend/src/app/features/work-packages/components/wp-new/wp-create.component.ts
index c3487f896e8..4ad392d48d0 100644
--- a/frontend/src/app/features/work-packages/components/wp-new/wp-create.component.ts
+++ b/frontend/src/app/features/work-packages/components/wp-new/wp-create.component.ts
@@ -48,6 +48,7 @@ import { APIV3Service } from 'core-app/core/apiv3/api-v3.service';
import { HalSource } from 'core-app/features/hal/resources/hal-resource';
import { OpTitleService } from 'core-app/core/html/op-title.service';
import { WorkPackageCreateService } from './wp-create.service';
+import { HalError } from 'core-app/features/hal/services/hal-error';
@Directive()
export class WorkPackageCreateComponent extends UntilDestroyedMixin implements OnInit {
@@ -152,8 +153,8 @@ export class WorkPackageCreateComponent extends UntilDestroyedMixin implements O
});
}
})
- .catch((error:any) => {
- if (error.errorIdentifier === 'urn:openproject-org:api:v3:errors:MissingPermission') {
+ .catch((error:unknown) => {
+ if (error instanceof HalError && error.errorIdentifier === 'urn:openproject-org:api:v3:errors:MissingPermission') {
this.apiV3Service.root.get().subscribe((root:RootResource) => {
if (!root.user) {
// Not logged in
diff --git a/frontend/src/app/shared/components/fields/edit/edit-form/edit-form.ts b/frontend/src/app/shared/components/fields/edit/edit-form/edit-form.ts
index 9f7a331c029..eb5a63c1d9a 100644
--- a/frontend/src/app/shared/components/fields/edit/edit-form/edit-form.ts
+++ b/frontend/src/app/shared/components/fields/edit/edit-form/edit-form.ts
@@ -41,6 +41,7 @@ import { InjectField } from 'core-app/shared/helpers/angular/inject-field.decora
import { HalResourceNotificationService } from 'core-app/features/hal/services/hal-resource-notification.service';
import { ErrorResource } from 'core-app/features/hal/resources/error-resource';
import isNewResource from 'core-app/features/hal/helpers/is-new-resource';
+import { HalError } from 'core-app/features/hal/services/hal-error';
export const activeFieldContainerClassName = 'inline-edit--active-field';
export const activeFieldClassName = 'inline-edit--field';
@@ -193,8 +194,8 @@ export abstract class EditForm<T extends HalResource = HalResource> {
.catch((error:ErrorResource|unknown) => {
this.halNotification.handleRawError(error, this.resource);
- if (error instanceof ErrorResource) {
- this.handleSubmissionErrors(error);
+ if (error instanceof HalError) {
+ this.handleSubmissionErrors(error.resource);
reject();
}
@@ -226,12 +227,12 @@ export abstract class EditForm<T extends HalResource = HalResource> {
});
}
- protected handleSubmissionErrors(error:any) {
+ protected handleSubmissionErrors(error:ErrorResource):void {
// Process single API errors
this.handleErroneousAttributes(error);
}
- protected handleErroneousAttributes(error:any) {
+ protected handleErroneousAttributes(error:ErrorResource):void {
// Get attributes withe errors
const erroneousAttributes = error.getInvolvedAttributes();
@@ -241,7 +242,7 @@ export abstract class EditForm<T extends HalResource = HalResource> {
return;
}
- return this.setErrorsForFields(erroneousAttributes);
+ this.setErrorsForFields(erroneousAttributes);
}
private setErrorsForFields(erroneousFields:string[]) {
diff --git a/frontend/src/app/shared/components/work-package-graphs/configuration/wp-graph-configuration.service.ts b/frontend/src/app/shared/components/work-package-graphs/configuration/wp-graph-configuration.service.ts
index 7289e1aa37d..e71086ced71 100644
--- a/frontend/src/app/shared/components/work-package-graphs/configuration/wp-graph-configuration.service.ts
+++ b/frontend/src/app/shared/components/work-package-graphs/configuration/wp-graph-configuration.service.ts
@@ -21,7 +21,7 @@ export class WpGraphConfigurationService {
private _forms:{ [id:string]:QueryFormResource } = {};
- private _formsPromise:Promise<void[]>|null;
+ private _formsPromise:Promise<unknown>|null;
constructor(
readonly I18n:I18nService,