Custom exceptions handler

Hi all,
In the server side, I want to throw a custom exception(including key and message ) like this.


public class MyCustomException extends RuntimeException {
	private final String key;

	public String getKey() {
		return key;
	}

	public MyCustomException(String key, String message) {
		super(message);
		this.key = key;
	}
}

But the GenericThrowableMapper of com.mgmtp.a12.dataservices.server.rest.exception.mapping.DataServicesExceptionsHandler always catch this exception and returns the result with key=unknown.
I want the key is also returned so I create my own mapping

@Log4j2
@ControllerAdvice
public class MyExceptionsHandler extends ResponseEntityExceptionHandler {

	@ExceptionHandler(value = {MyCustomException.class})
	public ResponseEntity<Object> handleMyCustomException(MyCustomException ex, WebRequest request) {
		return handleExceptionInternal(ex, "body of response" + ex.getMessage() + ex.getKey(),
				new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
	}
}

But it does not work.
GenericThrowableMapper still catch my exception and handle itself.

From what the document says, I think it is possible to create custom exception mapping.
Is there anything I should do now to make it work?
Thanks a lot!
Version using data-service: 35.0.6

Hello Q,

There are 2 cases you might encounter:

  1. The bean of MyExceptionsHandler is not initialized.
  2. MyExceptionsHandler bean is initialized after DataServicesExceptionsHandler.

If you are facing the second case, you can adjust the position of initializing your bean first. The simplest way is to use @Order(Ordered.HIGHEST_PRECEDENCE). :wink:

@Log4j2
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyExceptionsHandler extends ResponseEntityExceptionHandler {

	@ExceptionHandler(value = {MyCustomException.class})
	public ResponseEntity<Object> handleMyCustomException(MyCustomException ex, WebRequest request) {
		return handleExceptionInternal(ex, "body of response" + ex.getMessage() + ex.getKey(),
				new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
	}
}

Additional detail: I encounter problem 2. I used AutoConfigureOrder, but it didn’t work, and thought that order is not a problem.

Anyway, thank you very much!

I think @Order is not intended to select which bean Spring should instantiate but to sort bean instances of same interface for collection autowiring, as described here: @Order in Spring | Baeldung

Instead you could try to use @Primary in MyExceptionHandler and eventually subclass it from DataServicesExceptionHandler