type = $type; $this->code = $code; $this->message = $message; $this->param = $param; } /** * Create an invalid request error. * * @param string $code Implementation-defined error code. * @param string $message Human-readable error message. * @param string|null $param RFC 9535 JSONPath (optional). * @return Error */ public static function invalid_request( $code, $message, $param = null ) { return new self( ErrorType::INVALID_REQUEST, $code, $message, $param ); } /** * Create a request not idempotent error. * * @param string $code Implementation-defined error code. * @param string $message Human-readable error message. * @param string|null $param RFC 9535 JSONPath (optional). * @return Error */ public static function request_not_idempotent( $code, $message, $param = null ) { return new self( ErrorType::REQUEST_NOT_IDEMPOTENT, $code, $message, $param ); } /** * Create a processing error. * * @param string $code Implementation-defined error code. * @param string $message Human-readable error message. * @param string|null $param RFC 9535 JSONPath (optional). * @return Error */ public static function processing_error( $code, $message, $param = null ) { return new self( ErrorType::PROCESSING_ERROR, $code, $message, $param ); } /** * Create a service unavailable error. * * @param string $code Implementation-defined error code. * @param string $message Human-readable error message. * @param string|null $param RFC 9535 JSONPath (optional). * @return Error */ public static function service_unavailable( $code, $message, $param = null ) { return new self( ErrorType::SERVICE_UNAVAILABLE, $code, $message, $param ); } /** * Convert the error to a WP_REST_Response. * * @return WP_REST_Response WordPress REST API response object */ public function to_rest_response() { $data = array( 'type' => $this->type, 'code' => $this->code, 'message' => $this->message, ); if ( null !== $this->param ) { $data['param'] = $this->param; } $status_code = $this->get_http_status_code(); return new WP_REST_Response( $data, $status_code ); } /** * Determine HTTP status code based on error type. * * @return int HTTP status code */ private function get_http_status_code() { switch ( $this->type ) { case ErrorType::INVALID_REQUEST: return 400; case ErrorType::REQUEST_NOT_IDEMPOTENT: return 409; case ErrorType::PROCESSING_ERROR: return 500; case ErrorType::SERVICE_UNAVAILABLE: return 503; default: return 500; } } }