【问题标题】:Spring ControllerAdvice not being called on exceptionsSpring ControllerAdvice 没有被异常调用
【发布时间】:2017-11-17 16:19:56
【问题描述】:

虽然我定义了 ControllerAdvice 来处理异常,但我没有看到它被调用。 这是我的代码,请您指教

    public class RestError {   
        private String code;
        private String message;

    public RestError(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getCode() { return code; }

    public String getMessage() { return message; }
}


public class RestException extends RuntimeException {

   private String errorCode;
   private String errorMessage;

    public RestException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

控制器建议

@Controller
public class RestController {

    private static final Logger LOG = Logger.getLogger(RestController.class);
    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void echo(@RequestParam(value = "clientVersion", required = false) String clientVersion,
                     @RequestParam(value = "applicationName", required = false) String applicationName,
                     HttpServletRequest httpRequest) {
        LOG.info("Throwing exception...");
        throw new RestException("9999", "Invoke Exception Handler");
    }
}

我看到 spring 正在创建 GlobalExceptionHandler 对象,但它没有被调用。 这里是Full code

我正在使用 Spring 4.3.0 框架并通过 maven 在码头容器中运行。 请帮帮我

【问题讨论】:

  • 尝试添加@ControllerAdvice(basePackageClasses = RestController.class)
  • 不走运@pvpkiran

标签: spring exceptionhandler


【解决方案1】:

你需要添加

<mvc:annotation-driven/>

到您的 xml 以启用 ControllerAdvice。 另外不要忘记为此添加名称空间和架构定义

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

【讨论】:

猜你喜欢
  • 2014-08-26
  • 1970-01-01
  • 2017-01-23
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
相关资源
最近更新 更多