在我的REST服务应用程序中,我计划创建一个@ControllerAdvice
类来捕获控制器抛出异常并根据错误类型返回ResponseEntity
个对象。
但是我已经有一个实现@RestController
接口的ErrorController
类来捕获所有异常。
这两个是否以任何方式干涉?
在ErrorController
存在时,@ControllerAdvice
会调用哪些情况?
编辑:
请求的ErrorController
代码
@RestController
public class ControllerCustomError implements ErrorController{
//error json object
public class ErrorJson {
public Integer status;
public String error;
public String message;
public String timeStamp;
public String trace;
public ErrorJson(int status, Map<String, Object> errorAttributes) {
this.status = status;
this.error = (String) errorAttributes.get("error");
this.message = (String) errorAttributes.get("message");
this.timeStamp = errorAttributes.get("timestamp").toString();
this.trace = (String) errorAttributes.get("trace");
}
}
private static final String PATH = "/error";
@Value("${hybus.error.stacktrace.include}")
private boolean includeStackTrace = false;
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(value = PATH)
ErrorJson error(HttpServletRequest request, HttpServletResponse response) {
// Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring.
// Here we just define response body.
return new ErrorJson(response.getStatus(), getErrorAttributes(request, includeStackTrace));
}
@Override
public String getErrorPath() {
return PATH;
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
}
答案 0 :(得分:1)
ErrorController
的实现用于提供自定义的whitelabel错误页面。
用@ControllerAdvise
注释的类用于为整个应用程序添加全局异常处理逻辑。因此,您的应用程序中有多个控制器。
如果在您的应用程序中未找到请求或页面的映射,则spring将回退到“ whitelabel错误页面”。在这种情况下,它将是ErrorController