Code ví dụ Spring Boot xử lý Exception, lỗi 404

Code ví dụ Spring Boot xử lý Exception, lỗi 404.

Spring Boot Exception Handling

Trong phần Spring MVC mình có thực hiện xử lý lỗi trả về từ server (500, 404, 403 …) với HTTP Status Code, annotation @ExceptionHandler hoặc @ControllerAdvice

(Xem lại: Code ví dụ xử lý Exception, Exception Handling Spring MVC)

Ngoài những cách trên, trong Spring Boot ta còn có thể bắt và xử lý lỗi theo một cách đơn giản hơn là thừa kế interface ErrorController và override lại method getErrorPath()ví dụ:

@Controller
public class HandleErrorController implements ErrorController {

  @RequestMapping("/error")
  public String handleError(HttpServletRequest request) {
    // do something
    return "error";
  }

  @Override
  public String getErrorPath() {
    return "/error";
  }
}

Method getErrorPath() sẽ định nghĩa url thực hiện xử lý khi lỗi xảy ra. Trong đoạn code trên method getErrorPath() trả về giá trị /error do đó khi có lỗi nó sẽ chuyển tới uri /error để xử lý.

@RequestMapping("/error") thực hiện xử lý cho uri /error (tức là thực hiện xử lý lỗi) bạn có thể dựa vào request để check status code (404, 500…) hoặc lấy các parameter để trả về trang lỗi thích hợp, ở đây mình mặc định trả về trang error.html

Code ví dụ

Code ví dụ Spring Boot xử lý Exception, lỗi 404  Code ví dụ Spring Boot xử lý Exception, lỗi 404

Cấu trúc Project

Code ví dụ Spring Boot xử lý Exception, lỗi 404

Controller thực hiện xử lý exception:

package stackjava.com.sbexceptionhandler.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HandleErrorController implements ErrorController {

  @RequestMapping("/error")
  public String handleError(HttpServletRequest request) {
    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    if (status != null) {
      Integer statusCode = Integer.valueOf(status.toString());
      if (statusCode == HttpStatus.NOT_FOUND.value()) {
        return "error-404";
      } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
        return "error-500";
      }
    }
    return "error";
  }

  @Override
  public String getErrorPath() {
    return "/error";
  }
}

Ở đây mình dựa theo HTTP status code trong request để trả về trang lỗi thích hợp, ví dụ với status code = 404 thì mình sẽ trả về trang error-404.html

Trang view:

<!DOCTYPE html>
<html>
<body>
<h1>404</h1>
<h2>Page not found</h2>
<a href="/">Go Home</a>
</body>
</html>

Demo:

Ví dụ spring boot xử lý lỗi 404

Rõ ràng mình chưa định nghĩa page trả về cho uri / do đó khi chạy nó sẽ báo lỗi Page not found.

Nếu trong trường hợp trên mình không cài đặt interface ErrorController thì nó sẽ trả về trang lỗi mặc định sau:

 

Okay, done!

Download code ví dụ trên tại đây.

 

References:

https://docs.spring.io/…/howto-actuator.html

stackjava.com