Bài viết này sẽ hướng dẫn bạn cách xử lý exception với Spring Framework

1. Giới thiệu

Spring Framework cung cấp chúng ta rất nhiều cơ chế handle Exception, tùy theo trường hợp các bạn có thể xử lý Exception theo loại Exception, theo từng Controller, hoặc theo Response Code.

Dưới đây sẽ giới thiệu đến các bạn các cách handle exception trong Spring, để các bạn có thể tìm hiểu và áp dụng vào Project của mình.

2. Giải pháp

2.1 @ExceptionHandler cho tầng Controller:

Chúng ta bắt đầu với đoạn code sau:

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @ExceptionHandler({CustomException.class, CustomException2.class})
    public ResponseEntity<Object> handleCustomException(CustomException exception){
        //handle exception
        ApiError apiError = new ApiError(EXCEPTION_KEY);
        apiError.setMessage(ex.getMessage());
        return buildResponseEntity(apiError);
        
    }
}

Ưu điểm: Giúp gom nhóm các xử lý ngoại lệ cho 1 Controller. Ví dụ chúng ta có class UserController để quản lý dữ liệu thông tin người dùng, có một số lỗi thường gặp: UserNotFoundException (không tìm thấy dữ liệu), UserBlockedException(người dùng bị khóa tài khoản),... tất cả những exception này sẽ được gom nhóm tập trung tạo UserController, lập trình viên dễ dàng maintain code hơn và đặc biệt Spring cũng giúp chúng ta gom nhóm một vài Exception để dùng chung những method xử lý.

Nhược điểm: Chỉ áp dụng được cho phạm vi 1 Controller, không áp dụng được ở mức Application. 

 

2.2 HandlerExceptionResolver cho tầng Application:

ResponseStatusExceptionResolver:  Xử lý Exception theo Response Code

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException() {
        super();
    }
    public ResourceNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
    public ResourceNotFoundException(String message) {
        super(message);
    }
    public ResourceNotFoundException(Throwable cause) {
        super(cause);
    }
}

Như giới thiệu phương pháp này giúp chúng ta gom nhóm các Exception theo Responsse code để xử lý. 

@ControllerAdvice

@ControllerAdvice là một annotation đánh dấu một method được trigger sau khi các hàm trong các Controller được thực thi, kết hợp đồng thời với annotation @ExceptionHandler chúng ta sẽ có được 1 method handle exception cả các method của các class khác, package khác.

@ControllerAdvice
public class GlobalExceptionHandling {
  @ExceptionHandler(IOException.class)
  private ModelAndView processIOException(IOException ex) {
    ModelAndView model = new ModelAndView("error");
    model.addObject("error", ex.getMessage());
    return model;
  }
}

 

3. Tổng kết

Ở trên,  bài viết đã giới thiệu đến các bạn các phương pháp dùng để handle Exception khi dùng Spring Framework. Trong các bài viết sau chúng ta sẽ làm một ví dụ hoàn chỉnh về xử lí Exception, ghi lại log trace để tìm bug và trả về message cho người dùng.

minhnhatict@gmail.com