Support » Developing with WordPress » How to pass error code from wp_error() to PHP exception class?

  • Resolved xootixsupport



    I am using wp_error class to handle errors.
    Also when I use PHP throw new Exception , I find no way to pass an error code from wp_error() to Exception class.
    Exception class takes second parameter as getCode(). However the error codes from wp_error() class are in string form.
    Is there any wordpress way to handle such issue?
    Or the only option we have is to extend exception class?

            $error = new WP_Error();
            //Some validation
                $error_code = $error->get_error_code(); //returns "my-error-code" (String)
                throw new Exception( "Error thrown"); //How to send error code
        } catch{
            //Receive error code here

    Thanks a lot !

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    Essentially, WP error “codes” are not compatible with Exception codes. I suppose you could create some sort of lookup table for common error strings and assign an appropriate code. Default to 0 if there is no match. WP_Error codes are completely arbitrary and failure to match is likely.

    Or you could concatenate both WP_Error code and message together to pass as the Exception message and simply use code 0 for all errors. The best approach depends on what you plan to do to handle errors.

    I am really, I forgot to check “Notify me of follow-up replies via email”
    The problem comes when you are dealing with other plugins & they throw the wp error codes.
    So it is essential to know the code value.
    Anyway, I created the custom exception class from which I can pass my custom parameter.
    Thanks for your help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to pass error code from wp_error() to PHP exception class?’ is closed to new replies.