import { Component, Injectable, Input } from '@angular/core'; import { Response } from '@angular/http'; import { LocaleService } from './i18n'; import { Observable } from 'rxjs/Observable'; export interface IError { code: string | number, message: string, httpCode?: number } export const DEFAULT_APP_ERROR_STATUS_CODE = 418; export const ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG"; export const ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE"; export class ErrorCodes { public static UNEXPECTED_ERROR = 1000; public static INVALID_CREDENTIALS = 1001; public static UNAUTHORIZED_ACCESS = 1002; public static NOT_FOUND = 1003; public static INVALID_FORMAT = 1004; public static WRONG_STATUS = 1005; public static INVALID_LICENSE_REQUEST_DATA = 1100; public static LICENSE_NOT_READY_FOR_RENEW = 1101; public static LICENSE_DATA_IS_NOT_VALID = 1102; public static LICENSE_IS_EXPIRED = 1103; public static INVALID_REQUEST_DATA = 1201; public static INVALID_REQUEST_DATA_FORMAT = 1202; public static BLOCKED_REQUEST_DATA = 1203; public static DUPLICATED_REQUEST_DATA = 1204; public static NO_AVAILABLE_LICENSES = 1205; public static INVALID_DATA = 1301; } @Injectable() export class BasicService { constructor(protected $L: LocaleService) { } public setViewData(callback: any) { setTimeout(callback, 0); } public processErrorResponse(errorResponse: Response) { // In a real world app, we might use a remote logging infrastructure var error: IError = {}; error.httpCode = errorResponse.status; error.code = errorResponse.headers.get(ERROR_CODE_MESSAGE_HEADER) || error.httpCode; if (errorResponse.status === 403 /* forbidden */) { error.message = this.$L.get('Invalid credentials'); error.code = ErrorCodes.INVALID_CREDENTIALS; } else if (errorResponse.status === 401 /* unauthorized */) { error.message = this.$L.get('Action not allowed for current user'); error.code = ErrorCodes.UNAUTHORIZED_ACCESS; } else if (errorResponse.status === 418 /* Teapot */) { error.message = errorResponse.headers.get(ERROR_MESSAGE_HEADER) || errorResponse.statusText || this.$L.get('Unknown'); } else { error.message = this.$L.get(`Unexpected error HTTP (${error.httpCode}) accessing to server. Contact with the administrator.`); } return Observable.throw(error); } }