unit XData.Sys.Exceptions;

interface

uses
  SysUtils;

type
  EXDataException = class(Exception)
  strict private
    FErrorCode: string;
    function GetErrorCode: string;
    procedure SetErrorCode(const Value: string);
  public
    property ErrorCode: string read GetErrorCode write SetErrorCode;
  end;

  EXDataHttpException = class(EXDataException)
  strict private
    FStatusCode: integer;
  public
    constructor Create(const AStatusCode: integer; const Msg: string); overload;
    constructor Create(const AStatusCode: integer; const AErrorCode: string; const Msg: string); overload;
    constructor CreateFmt(const AStatusCode: integer; const Msg: string; const Args: array of const);
    property StatusCode: integer read FStatusCode write FStatusCode;
  end;

  EXDataHttpUnauthorized = class(EXDataHttpException)
  public
    constructor Create(const Msg: string);
  end;

  EXDataHttpForbidden = class(EXDataHttpException)
  public
    constructor Create(const Msg: string);
  end;

implementation

{ EXDataHttpException }

constructor EXDataHttpException.Create(const AStatusCode: integer; const Msg: string);
begin
  inherited Create(Msg);
  FStatusCode := AStatusCode;
end;

constructor EXDataHttpException.Create(const AStatusCode: integer;
  const AErrorCode, Msg: string);
begin
  inherited Create(Msg);
  FStatusCode := AStatusCode;
  Self.ErrorCode := AErrorCode;
end;

constructor EXDataHttpException.CreateFmt(const AStatusCode: integer; const Msg: string;
  const Args: array of const);
begin
  Create(AStatusCode, Format(Msg, Args));
end;

{ EXDataException }

function EXDataException.GetErrorCode: string;
var
  S: string;
begin
  if FErrorCode <> '' then
    Exit(FErrorCode);

  S := Self.ClassName;
  Delete(S, 1, 1); // Remove the "E"
  if Copy(S, 1, Length('XDataHttp')) = 'XDataHttp' then
    Delete(S, 1, Length('XDataHttp'))
  else
  if Copy(S, 1, Length('XData')) = 'XData' then
    Delete(S, 1, Length('XData'));
  Result := S;
end;

{ EXDataUnauthorizedException }

constructor EXDataHttpUnauthorized.Create(const Msg: string);
begin
  inherited Create(401, Msg);
end;

{ EXDataForbiddenException }

constructor EXDataHttpForbidden.Create(const Msg: string);
begin
  inherited Create(403, Msg);
end;

procedure EXDataException.SetErrorCode(const Value: string);
begin
  FErrorCode := Value;
end;

end.
