samedi 25 juillet 2020

catching and re throwing same custom exception

I have a Spring JobRunner Component that has a run() method which throws my custom exception:

public Response run(final Request request, final String id) {
    try {
        execution = jobLauncher.run(job, parameters);
    } catch (JobExecutionAlreadyRunningException e) {
        throw new MyCustomException("already running ", e);
    } catch (JobRestartException e) {         
        throw new MyCustomException("Restart Exception", e);
    } 
    return generateResponse(request, id, execution);
}

In my service class, I call this run() method inside process()

  protected Response process(final Request request, final String id) {
      //get entity
      //save
      //bla bla
    Response response;
    try {
        response = jobRunner.run(request, id);
        updateStatus(entity, response.getStatus(), "");
    } catch (MyCustomException ex) {
        updateStatus(entity, FAILED);
        throw new MyCustomException(ex.getMessage(), ex);
    }
}

You will notice I am catching MyCustomException and rethrowing again. I have to catch because I need to update the status accordingly here in the service class as it has a repository dependency to update status in db for tracking purpose.

I am also rethrowing because attached to this custom exception is a ControllerAdvice for api requests so it responds accordingly.

What I would like to know, is this a good design or a bad practice ? What could I change if anything ?

Aucun commentaire:

Enregistrer un commentaire