Spring @ControllerAdvice vs ErrorController

2019-04-21 21:06发布

问题:

In my REST service app, I am planning to create a @ControllerAdvice class to catch controller thrown exceptions and return ResponseEntity objects according to the error type.

But I already have a @RestController class implementing the ErrorController interface to catch all exceptions.

Do these two interfere in any manner? In which cases will ErrorController be called when @ControllerAdvice exists?

Edit: The ErrorController code as requested

@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:

An implementation of the ErrorController is used to provide a custom whitelabel error page.

A class annotated with @ControllerAdvise is used to add a global exception handling logic for the whole application. Thus, more than one controller in your application.

If in your application there is no mapping found for a request or page then spring will fallback to the 'whitelabel error page'. And in this case it will be the custom implementation of ErrorController