如何在@ControllerAdvice 中打印Controller 方法名称?

How to print the Controller method name in @ControllerAdvice?

我经历了 link: 很多次,但我希望在 @ControllerAdvice class.

中获取控制器方法名称

这是我的 CustomHandler Class。

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    ........
    ..........
    ..........

    @ExceptionHandler({DataExistsException.class})
    public ResponseEntity<Object> handleDataExistsException(RuntimeException e, WebRequest request, HttpServletRequest httpRequest, HttpServletResponse response, HandlerMethod handlerMethod) {
        // Here I am looking to print Controller endpoint method name

        LoggingUtil.printJsonReq(httpRequest, HttpStatus.valueOf("BAD_REQUEST").value(), LoggingUtil.getTime(httpRequest), null, response);
        return handleExceptionInternal(e, getErrors(error), getHeaders(), HttpStatus.BAD_REQUEST, request);
    }
}

HandlerMethod 应该给你这个信息。引用文档:

Encapsulates information about a handler method consisting of a method and a bean. Provides convenient access to method parameters, the method return value, method annotations, etc.

所以你可以使用:

Method method = handlerMethod.getMethod();

您可以从 RuntimeException 中找出方法名称,这样就可以了

 e.getStackTrace()[0].getMethodName();