Which statement correctly describes @ExceptionHandler and @ControllerAdvice?
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "@ExceptionHandler in a controller handles exceptions for that controller; @ControllerAdvice can apply such handlers globally". Phương thức @ExceptionHandler khai báo trong một controller chỉ bắt ngoại lệ ném ra từ các handler của chính controller đó; muốn dùng chung cho nhiều controller, ta đặt các phương thức @ExceptionHandler vào một lớp @ControllerAdvice hoặc @RestControllerAdvice, và mặc định lớp này áp cho mọi controller, có thể thu hẹp bằng basePackages hay assignableTypes. Phát biểu "handle exceptions across all controllers by default; @ControllerAdvice limits them to one controller" nói ngược hoàn toàn vai trò của hai annotation. Phát biểu "only works with REST controllers; @ControllerAdvice only with MVC controllers" sai vì cả hai dùng được cho controller trả view lẫn controller REST. "Both are deprecated in favor of filters" sai vì cả hai vẫn là cơ chế chính thức trong Spring hiện nay; filter chạy trước DispatcherServlet nên không thay được việc xử lý ngoại lệ ở tầng handler.