小编典典

Spring @ControllerAdvice与ErrorController

spring-boot

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

阅读 355

收藏
2020-05-30

共1个答案

小编典典

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

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

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

2020-05-30