如何在 Spring MVC 中的@controllerAdvice 或@RestControllerAdvice 中查找控制器名称?
How to find controller name in @controllerAdvice or @RestControllerAdvice in Spring MVC?
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<Error> handle(NoHandlerFoundException ex){
String message = "HTTP " + ex.getHttpMethod() + " for " + ex.getRequestURL() + " is not supported.";
Error error = new Error(HttpStatus.NOT_FOUND.value(), message);
return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
}
}
- 我正在使用@ControllerAdvice 和@ExceptionHandler。
- 我需要获取发生异常的控制器class名称和包名称或class句柄方法中的对象
这应该有效
@ControllerAdvice
class AdviceA {
@ExceptionHandler({SomeException.class})
public ResponseEntity<String> handleSomeException(SomeException pe, HandlerMethod handlerMethod) {
Class controllerClass = handlerMethod.getMethod().getDeclaringClass();
//controllerClass.toString will give you fully qualified name
return new ResponseEntity<>("SomeString", HttpStatus.BAD_REQUEST);
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<Error> handle(NoHandlerFoundException ex){
String message = "HTTP " + ex.getHttpMethod() + " for " + ex.getRequestURL() + " is not supported.";
Error error = new Error(HttpStatus.NOT_FOUND.value(), message);
return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
}
}
- 我正在使用@ControllerAdvice 和@ExceptionHandler。
- 我需要获取发生异常的控制器class名称和包名称或class句柄方法中的对象
这应该有效
@ControllerAdvice
class AdviceA {
@ExceptionHandler({SomeException.class})
public ResponseEntity<String> handleSomeException(SomeException pe, HandlerMethod handlerMethod) {
Class controllerClass = handlerMethod.getMethod().getDeclaringClass();
//controllerClass.toString will give you fully qualified name
return new ResponseEntity<>("SomeString", HttpStatus.BAD_REQUEST);
}