สำหรับ Exception Handler เราจะสร้าง class ที่ใช้
@ControllerAdvice
ดังนี้
package com.example.exception;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.LinkedHashMap;
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(value = {ExceptionWrapper.class})(value = {exception_class.class})
public ResponseEntity<Object> exceptionHandler(exception_class ex) {
// Handle specific exception then return ResponseEntity
return new ResponseEntity(ex,HttpStatus.BAD_REQUEST);
}
}
โดยที่
exception_class เป็นชื่อของ Exception Class ที่ต้อง handle
คำอธิบายเพิ่มเติม
-
@ControllerAdvice
- อนุญาตให้เรา apply เทคนิคใน class ข้างใต้มันกับทุกๆ controller ของเรา (อ่านเพิ่มเติมที่ ControllerAdvice)
@ExceptionHandler
- ใช้เพื่อระบุว่า method ข้างใต้มันเป็น Exception handling methods (อ่านเพิ่มเติมที่ ExceptionHandler)