在Spring Boot中,可以通過以下幾種方式來處理錯誤和異常:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
}
}
@RestController
public class MyController {
@RequestMapping("/test")
public String test() {
throw new RuntimeException("Test exception");
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
}
}
@ControllerAdvice
public class GlobalErrorHandler {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found: " + e.getMessage());
}
}
@Controller
public class MyErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError() {
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
通過以上方式,可以靈活地處理Spring Boot應用中的錯誤和異常,提高應用的健壯性和用戶體驗。