Error Handling

The package uses Exceptions as a way to handle errors. The exceptions can be thrown from anywhere in your code, and the package will automatically handle them and generate the appropriate OCPI response. Exception handling is done by the OcpiExceptionFilter attribute, which is automatically applied to all controllers that inherit from the OcpiController base class. Exceptions can be populated with a custom data payload, which will be included in the OCPI response.

You can use the OcpiControllerBase class if you want to avoid the default exception handling. The only difference between the OcpiController and OcpiControllerBase classes is that the OcpiController class has the OcpiExceptionFilter attribute applied to it.

Overview of the package's error handling capabilities

When an exception gets thrown within a method that was called by an OCPI controller, this exception will bubble up to the controller and get handled by the OcpiExceptionFilter attribute. The attribute will then generate an appropriate OCPI response based on the exception type and the exception data payload. Further request handling will be aborted, and the response will be returned to the client.

The package contains a number of predefined exceptions which you can use to handle common error scenarios. You can also create your own custom exceptions if you need to handle more specific error scenarios.

These exception functionality is based on the BitzArt.ApiExceptions nuget package. Refer to that package's documentation for more information on how to interact with the exception payloads.

Predefined OCPI exceptions and how to use them

The package contains a number of predefined exceptions which you can use to handle common error scenarios. You can create these exceptions using the OcpiException static class:

throw OcpiException.ClientApiError();
// will return a ClientApiError OCPI status code and a default message for this type of error.

throw OcpiException.ClientApiError("Custom error message");
// will return a ClientApiError OCPI status code and a custom message.

throw OcpiException.ClientApiError("Custom error message", innerException);
// will return a ClientApiError OCPI status code, a custom message, and an inner exception.

Returning a custom OCPI status code

Return a custom OCPI status code by calling the Custom method from the OcpiException static class:

int customStatusCode = 1;
throw OcpiException.Custom("custom error message", customStatusCode);

Creating custom OCPI exceptions

You can create your own custom exceptions by inheriting from the OcpiExceptionBase class:

public class MyCustomOcpiException : OcpiExceptionBase
{
    public MyCustomOcpiException() : base("custom message", OcpiStatusCodes.ClientApiError)
    {
    }
}