【发布时间】:2016-06-17 09:37:24
【问题描述】:
我正在尝试使用 @ControllerAdvice 处理和响应带有自定义错误(消息)的请求以进行 Rest API 调用。
尝试配置和设置并在文档中指定效果不佳。这是我的代码sn-p
在 RestController 中,方法有以下语句
if(object==null){
throw new CustomGenericException("E_001", "Null error");
}
CustomGenericException 类如下
public class CustomGenericException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
自定义异常处理类如下
@ControllerAdvice
public class GlobalExceptionController{
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(CustomGenericException.class)
public @ResponseBody String handleCustomException(CustomGenericException ex) {
System.out.println(ex.getErrCode());
return ex.getErrMsg();
}
}
最后我在 dispatcher-servlet.xml 文件中有如下配置
<mvc:annotation-driven />
<context:component-scan base-package="com.xyz.pqr.controller" />
我面临的问题是执行以下语句时我得到空
throw new CustomGenericException("E_001", "Null error");
【问题讨论】:
-
你确定你的控制器建议被调用了吗?
-
根据在线教程,这是要进行的配置,我确实做到了。 SOP 没有打印意味着它没有被调用.. 倒是你帮我解决了这个问题。
-
你把建议放在哪里了?我的意思是什么包
-
另外,如果您添加配置并描述您的项目结构会很有用
-
我将 Advisor 放入了控制器包中
标签: java spring spring-mvc exception-handling