How to return custom html error codes

How to return a different HTML error code than 500 in a powerGateServer plugin

When an error is thrown in a powerGate Server plugin this always results in status code 500 being returned. DataServiceExceptions are ignored by WCF, but it is possible to manipulate the OData response of powerGateServer.

To do so first add a reference to your project to

  • System.ServiceModel
  • System.ServiceModel.Web

Afterwards you can override your statuscode in your Create, Update, Delete or Query functions. In case of an error code you also need to stop powerGateServer from returning an object. This can be seen in this sample code:

public override IEnumerable<Service> Query(IExpression<Service> expression)
{
    var outgoingResponse = System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse;
  outgoingResponse.StatusCode = HttpStatusCode.NotFound; //specify different status codes here
   outgoingResponse.StatusDescription = "Custom 404 error message";

    //in order to prevent powerGateServer from providing entities in the response the content of the response can be supprest, even thgouht this does not correspond to the definition of a valid OData error responses
    outgoingResponse.SuppressEntityBody = true;

    //...
}

In order to read the status code on the client we can use the $error variable that is set by powerGate in case of errors

function Get-HtmlError {
    $result = @{
        Success = $true
        StatusCode = 200
        Message = "It Works!"
    }

    if ($?) {
        Write-Host $result.Message
        return $result
    }

    $result.Success = $false
    $result.StatusCode = $Error[0].Exception.StatusCode
    $result.Message = $Error[0].Exception.Message

    Write-Host $result.Message
    return $result
}

Get-ERPObjects -EntitySet Materials
$htmlErrorResult = Get-HtmlError
if(-not $htmlErrorResult.Success) {
#Error occured. Handle it.
}

#Everything is fine.