Search code examples
javaexceptionwrapperlibrariesfido-u2f

Wrapping an exception when wrapping a third-party library


I have come across a small issue while I was making a simple API for the backend code of registration and login in a website with a FIDO device.

I am basically wrapping the yubico u2f library and making it even simpler to use. The problem that I have run at is with exceptions, I want to throw from my API to the backend server the com.yubico.u2f.exceptions.NoEligableDevicesException exception but I don't want my user (the backend developer) to ever have to see or import the yubico library.

Therefore my solution was to wrap that exception like so:

package com.github.dkanellis.fikey.exceptions;

import com.yubico.u2f.data.DeviceRegistration;

public class NoEligableDevicesException extends com.yubico.u2f.exceptions.NoEligableDevicesException {
    public NoEligableDevicesException(Iterable<? extends DeviceRegistration> devices, String message, Throwable cause) {
        super(devices, message, cause);
    }

    public NoEligableDevicesException(Iterable<? extends DeviceRegistration> devices, String message) {
        super(devices, message);
    }
}

and then throw to the user my exception that wraps the yubico exception. The problem is that this add complexity to my code and everytime the com.yubico.u2f.exceptions.NoEligableDevicesException exception occurs I have to catch it and throw the com.github.dkanellis.fikey.exceptions.NoEligableDevicesException.

Is there a better way to do this?


Solution

  • The problem is that this add complexity to my code and everytime the com.yubico.u2f.exceptions.NoEligableDevicesException exception occurs I have to catch it and throw the com.github.dkanellis.fikey.exceptions.NoEligableDevicesException.

    This is not a problem. This is actually the recommended way to propagate an Exception between different layers of your application. I had come across this excellent article on propagating an Exception recently. (It's a .Net article but still applicable for Java)

    Wrapping the actual Exception into your own Exception subclass gives you the flexibility to change the underlying dependencies of your API without breaking client code. The client code continues to depend on your Exception subclass.