Home > OS >  WebClient exception handler
WebClient exception handler

Time:01-17

I want to make exception handler for my WebClient, which calls internal API. I don't want to use onStatus() method, due to I have abstract web client with different methods where I have to process exceptions, so I have to copy paste each onStatus() in my every abstract method. I want to make something similar to the rest template approach: we can implement ResponseErrorHandler and add our implementation into resttemplate e.g. setExceptionHandler(ourImplementation). I want the one class to handle all the exceptions. Thanks for your advice in advance!

CodePudding user response:

You can do smth like that

@ControllerAdvice
public class ErrorControllerAdvice {
  @ExceptionHandler({RuntimeException.class})
  public ResponseEntity<?> handleRuntimeException(RuntimeException e) {
    log.error(e.getMessage(), e);
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
  }

  @ExceptionHandler({Exception.class})
  public ResponseEntity<?> handleRuntimeException(Exception e) {
    log.error(e.getMessage(), e);
    return ResponseEntity.status(HttpStatus.OK)
        .body(e.getMessage());
  }
}

CodePudding user response:

GithubSample

Here is the answer. I have used 2nd approach, it works.

  •  Tags:  
  • Related