33import java .io .BufferedReader ;
44import java .io .InputStreamReader ;
55import java .util .Map ;
6+ import java .util .function .Consumer ;
67
78public class PHPJava {
89 private final String PHP_BIN_PATH ;
@@ -11,6 +12,8 @@ public class PHPJava {
1112 private Map <String , String > env_vars ;
1213 private String response = null ;
1314
15+ private Consumer <String > ERR_CALLBACK ;
16+
1417 /**
1518 * Creates a PHPJava instance
1619 * @param php_bin_path PHP binary file path (e.g /usr/bin/php)
@@ -67,12 +70,11 @@ public void run(String php_filepath) throws Throwable {
6770 } catch (Throwable error ){
6871 String err = error .getMessage ();
6972
70- if (!this .NO_PHP_WARN && (err .contains ("PHP Warning:" ) || err .contains ("PHP Startup:" ))){
71- onError (err );
72- }
73+ if (!this .NO_PHP_WARN && (err .contains ("PHP Warning:" ) || err .contains ("PHP Startup:" ))) onError (err );
7374 }
7475
7576 assert process != null ;
77+
7678 try (BufferedReader reader = new BufferedReader (new InputStreamReader (process .getInputStream ()))){
7779 StringBuilder resBuilder = new StringBuilder ();
7880 String line ;
@@ -91,13 +93,19 @@ public void run(String php_filepath) throws Throwable {
9193 if (!errorBuilder .toString ().isEmpty ()){
9294 String err = new Throwable (errorBuilder .toString ()).getMessage ();
9395
94- if (!this .NO_PHP_WARN && (err .contains ("PHP Warning:" ) || err .contains ("PHP Startup:" ))){
95- onError (err );
96- }
96+ if (!this .NO_PHP_WARN && (err .contains ("PHP Warning:" ) || err .contains ("PHP Startup:" ))) onError (err );
9797 }
9898 }
9999 }
100100
101+ /**
102+ * Sets the function that will be called to handle the error instead of printing it into the console
103+ * @param cb The function to be executed on error
104+ */
105+ public void setErrorCallback (Consumer <String > cb ){
106+ this .ERR_CALLBACK = cb ;
107+ }
108+
101109 /**
102110 * Gets the result of the executed PHP file
103111 * @return The result of the PHP file, returns null if no results
@@ -107,10 +115,15 @@ public String getResult(){
107115 }
108116
109117 /**
110- * Error event listener, outputs error with System.err by default, it needs to be overridden
118+ * Error event listener, outputs error with System.err by default, to set custom error handler, use {@link #setErrorCallback}
111119 * @param error The error
112120 */
113- public void onError (String error ){
114- System .err .println (error );
121+ private void onError (String error ){
122+ if (this .ERR_CALLBACK == null ) {
123+ System .err .println (error );
124+ return ;
125+ }
126+
127+ this .ERR_CALLBACK .accept (error );
115128 }
116129}
0 commit comments