0

虽然我定义了 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 对象,但它没有被调用。这是完整代码

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

4

1 回答 1

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">
于 2017-11-17T18:56:39.613 回答