Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Spring Converter throw a custom exception instead of a ConversionFailedException?

I have a bunch of custom spring converters in my codebase something like:

public class ElasticSearchConverter implements Converter<RequestModel, ResponseModel> {
  @Override
  public final ResponseModel convert(RequestModel requestModel) {
    if(!requestModel.isValid()) {
      throw new ElasticSearchException("Request Model is not valid");
    }

    ... Implement converter
  }
}

I call those converters from a service by using the spring ConversionService

@Service
public class ElasticService {
  @Autowired
  private ConversionService conversionService;

  public ResponseModel getResponse(RequestModel requestModel) {

    //Throws ConversionFailedException instead of ElasticSearchException
    ResponseModel responseModel = conversionService.convert(requestModel, ResponseModel.class);

    return responseModel;
  }
}

My problem is when I throw my ElasticSearchException inside my ElasticSearchConverter it gets caught inside the spring ConversionUtils class and converted to a ConversionFailedException. I want to catch the specific ElasticSearchException that I'm throwing in my converter.

How can I catch a specific exception from a spring Converter class in my service class?

like image 695
Grammin Avatar asked Nov 07 '25 20:11

Grammin


1 Answers

You need to implement class that will handle your Exceptions

@ControllerAdvice
public class ExceptionTranslator {


    @ExceptionHandler(ConversionFailedException.class) //handle your Exception
    @ResponseStatus(HttpStatus.BadRequest) // Define the status you want to return
    @ResponseBody
    public ErrorDTO processElasticSearchException(ConversionFailedException ex) {
        return new ErrorDTO(); 
        /* Format your response as you need*/
    }
}

@ControllerAdvice "Classes with (the annotation) can be declared explicitly as Spring beans or auto-detected via classpath scanning" show documentation
@ExceptionHandler defines the exception you want to catch
@ResponseStatus defines the http response status
@ResponseBody Serialize automatically response as json object

For my projects, i define an ErrorDTO to format the response, you can do the same and you will just have to construct your object and to return it
You can also put the code you want to execute into this method and rise an other exception if needed

like image 152
nassim Avatar answered Nov 09 '25 13:11

nassim