在Java中,使用ResponseEntity處理異常的方法如下:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
注解創建一個全局異常處理類。這個類將包含處理特定異常的@ExceptionHandler
方法。@ControllerAdvice
public class GlobalExceptionHandler {
// ...
}
GlobalExceptionHandler
類中,添加一個或多個帶有@ExceptionHandler
注解的方法。這些方法將處理特定類型的異常。方法的參數應該是一個異常類型,返回值可以是一個ResponseEntity
對象。例如,處理NullPointerException
異常:
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
String errorMessage = "NullPointerException occurred: " + ex.getMessage();
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(errorMessage, httpStatus);
}
處理自定義異常CustomException
:
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
String errorMessage = "CustomException occurred: " + ex.getMessage();
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
return new ResponseEntity<>(errorMessage, httpStatus);
}
@ExceptionHandler
方法來處理異常。例如,拋出一個NullPointerException
:
@GetMapping("/example")
public String exampleMethod() {
String str = null;
return str.toUpperCase(); // This will throw a NullPointerException
}
GlobalExceptionHandler
類中添加更多的@ExceptionHandler
方法。通過這種方式,你可以使用ResponseEntity處理Java中的異常,并返回適當的HTTP狀態碼和錯誤消息。