我正在尝试使用@ControllerAdvice for Rest API调用来处理和响应带有自定义错误(消息)的请求。
尝试使用配置和设置并在文档中指定并不能很好地工作。这是我的代码片段
在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");
答案 0 :(得分:0)
我想出了解决方案,不要在尝试抛出自定义错误的方法中使用try / catch块。它有效。