没有在异常上调用Spring ControllerAdvice

时间:2017-11-17 16:19:57

标签: spring exceptionhandler

虽然我定义了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;
}

}

ControllerAdvice

@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在jetty容器中运行。 请帮帮我

1 个答案:

答案 0 :(得分:0)

您需要添加

<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">