Helidon: Custom exception with Exception Mapper

0
55

Having a custom exception is a standard programming practice. Instead of having various exceptions (Native), wrapping those exceptions with our well-defined custom business exceptions offers full control over our exception handling practices. In this article, I am going to explain, how to write custom exceptions with the Helidon framework during the microservice development.

Since the Helidon framework, simply follows Microprofile specification, we can use JAX-RS capabilities to get the job done.

How?

  1. Implement custom exception
  2. Implement custom exception mapper
  3. Bind the custom exception in the application

Next, we will go through each step in detail.

Custom exception (DailyApiException.java)

public class DailyApiException extends Exception {
    private int code = 500;

    public DailyApiException(String message) {
        super(message);
    }

    public DailyApiException(int code, String message) {
        super(message);
        this.code = code;
    }

    public DailyApiException(String message, Throwable cause) {
        super(message, cause);
    }

    public int getCode() {
        return code;
    }
}

Custom exception mapper (DailyApiExceptionMapper.java)

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class DailyApiExceptionMapper implements ExceptionMapper<DailyApiException> {
    @Override
    public Response toResponse(DailyApiException e) {
        Map<String, Object> entities = new HashMap<>();
        entities.put("code", e.getCode());
        entities.put("message", e.getMessage());
        return Response
                .status(e.getCode())
                .entity(entities)
                .build();
    }
}

Bind exception mapper into application

@ApplicationScoped
@ApplicationPath("/")
public class DailyApiApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        return CollectionsHelper.setOf(
                DailyApiExceptionMapper.class, //Exception mapper
                CountryApi.class
        );
    }
}

Finally, in our API implementation, we can directly throw the custom exception based on our business conditions like below,

@GET
Response all() throws DailyApiException;

@Path("{code}")
@GET
Response get(@PathParam("code") String code) throws DailyApiException;

I believe now you have got a clear understanding of how to implement custom exceptions in our APIs. Please share your feedback if you have any!

{ happy coding }