Spring @ControllerAdvice vs ErrorController

时间:2016-11-08 14:36:07

标签: spring spring-boot spring-mvc exception error-handling

在我的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);
    }
}

1 个答案:

答案 0 :(得分:1)

ErrorController的实现用于提供自定义的whitelabel错误页面。

@ControllerAdvise注释的类用于为整个应用程序添加全局异常处理逻辑。因此,您的应用程序中有多个控制器。

如果在您的应用程序中未找到请求或页面的映射,则spring将回退到“ whitelabel错误页面”。在这种情况下,它将是ErrorController

的自定义实现