在Java控制器中处理异常通常有以下几种方式:
@GetMapping("/example")
public ResponseEntity<String> example() {
try {
// 业务逻辑代码
return ResponseEntity.ok("Success");
} catch (Exception e) {
// 处理异常
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOException(IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An IO error occurred");
}
@ExceptionHandler(SQLException.class)
public ResponseEntity<String> handleSQLException(SQLException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("A SQL error occurred");
}
}
通过以上方式,可以在Java控制器中灵活处理异常,提高系统的稳定性和可靠性。