I am trying to build a GlobalExceptionHandler which extends AbstractErrorWebExceptionHandler
. I have custom exception classes which extends RuntimeException
. When I throw an exception I build a custom object which I need in the GlobalExceptionHandler to log and return custom json.
I am used to the MVC way of exception handing and webflux is new to me.
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) {
super(errorAttributes, resourceProperties, applicationContext);
this.setMessageWriters(configurer.getWriters());
}
@Override
protected RouterFunction < ServerResponse > getRoutingFunction(ErrorAttributes errorAttributes) {
// code here gets executed but I do not have access to custom objects I build when throwing exception.
return ...
}
// This code does not get executed.
@ExceptionHandler(CustomException.class)
public Mono < ServerResponse > customException(CustomException ex) {
// ex contains custom attributes I have created which needs to be logger here and returned
// use ex here to build and return custom json.
return ...;
}
When I throw an exception I build custom object and was hoping the global exception handler would contain this object.
if(error){
CustomExceptionObject o = CustomExceptionObject.builder()...build();
throw new CustomException( o ); // i need to access this in the exception handler.
}
Is this the correct way to handle exceptions or does webflux have another way to handle situations like these?