如何在Spring MVC中的@CONTRONTERADVICE或@RestControllerAdvice中找到控制器名称? [英] How to find controller name in @controllerAdvice or @RestControllerAdvice in Spring MVC?

查看:0
本文介绍了如何在Spring MVC中的@CONTRONTERADVICE或@RestControllerAdvice中找到控制器名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    @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);
        }

    }
  1. 我正在将@ControllerAdance与@ExceptionHandler一起使用。
  2. 我需要在Handle方法中获取发生异常的控制器类名和包名或类对象

推荐答案

这应该可以用

@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);
  }

这篇关于如何在Spring MVC中的@CONTRONTERADVICE或@RestControllerAdvice中找到控制器名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆