Search code examples
javaodatacustom-exceptions

Sending custom Exception Details with the Response in OData2


I am working in a web service project where olingo, odata2 are used with Java . I am using factory class that extends ODataJPAServiceFactory. I want to send custom status code and message in case any exception happens in the module. But can not find out how to send the custom exception details with the response. If anybody has faced the same issue or have some knowledge on this topic can you please share your valuables.

I am using REST API


Solution

  • Hi i finally got the solution:

    In Olingo V2 it is possible to override the "getCallback" method to use an own implementation of an ODataErrorCallback. Documentation can be found here: http://olingo.staging.apache.org/doc/odata2/tutorials/debug.html#error-callback And a sample here: org.apache.olingo.odata2.ref.processor.ScenarioServiceFactory

    In our use case you could (as simple example) add below listed code below into your code (or as example the JPA reference scenario factory (org.apache.olingo.odata2.jpa.processor.ref.web.JPAReferenceServiceFactory)).

    @Override
    public <T extends ODataCallback> T getCallback(Class<T> callbackInterface) {
      if(callbackInterface.isAssignableFrom(ODataErrorCallback.class)) {
       return (T) new MySampleErrorCallback();
    }
    return super.getCallback(callbackInterface);
    }
    
    private class MySampleErrorCallback implements ODataErrorCallback {
    @Override
    public ODataResponse handleError(ODataErrorContext context) throws  ODataApplicationException {
      LOG.error("Error...");
      return EntityProvider.writeErrorDocument(context);
    }
    

    }