cannot set 'name' of undefined when throwing exception - node.js

I was just trying Apache Thrift in nodejs before using it in my upcoming project wherein I ran into this error.
Here is my demo.thrift file
namespace js demo
typedef i32 int
enum Operation {
ADD = 1,
SUBTRACT = 2,
MULTIPLY = 3,
DIVIDE = 4
}
struct Work {
1: int num1 = 0,
2: int num2,
3: Operation op,
4: optional string comment
}
exception InvalidOperation {
1: int message,
2: string trace
}
service Calculator {
void ping()
double calculate(1: int logid, 2: Work w) throws (1: InvalidOperation oops),
oneway void zip()
}
Here is a part of the server.js
I use switch case to determine operation in server.js
// inside thrift.createServer
calculate: (logid, work, result) => {
let answer = null, oops = null;
switch(work.op) {
// Code related to Operation.ADD, Operation.SUBTRACT ...
default: {
console.log("ERROR!");
oops = InvalidOperation();
oops.message = work.op;
oops.trace = "Unknown Operation";
}
}
result(oops, answer);
}
When the client.js calls server with calculate(12345, { num1:1, num2:2, op: 10 })
Instead of returning an error it throws
TypeError: Cannot set property 'name' of undefined in demo_types.js:122
The part related to InvalidOperation in demo_types.js is
// Work related code
var InvalidOperation = module.exports.InvalidOperation = function(args) {
Thrift.TException.call(this, "InvalidOperation");
this.name = "InvalidOperation"; // points to here
this.message = null;
this.trace = null;
if (args) {
if (args.message !== undefined && args.message !== null) {
this.message = args.message;
}
if (args.trace !== undefined && args.trace !== null) {
this.trace = args.trace;
}
}
};
Thrift.inherits(InvalidOperation, Thrift.TException);
InvalidOperation.prototype.name = 'InvalidOperation';
// InvalidOperation.read & .write
Any idea why the error is being thrown?

Actually I realised why this error is being thrown. It is a plain old Javascript mistake.
oops = new InvalidOperation();
That's it.

Related

How To Use CompUtil To Parse With Plugin

When using the Alloy API to perform parsing on the following string:
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
I receive the following error:
Fatal error:
Parser Exception
at edu.mit.csail.sdg.alloy4compiler.parser.CompParser.alloy_parseStream(CompParser.java:2260)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseRecursively(CompUtil.java:178)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromFile(CompUtil.java:280)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromString(CompUtil.java:333)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil$parseEverything_fromString.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at MyOM.MyOMPlugin.Modularize(MyOMPlugin.groovy:107)
...
--------------------------------------------------------------------------
class file:
package MyOM
class MyOMPlugin extends Plugin{
void Modularize() throws Err{
//line 107 is the only line in the method and is below
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
}
}
I am performing this task in a groovy class file within a groovy project. The code works fine until I run it in conjunction with the plugin I am using.
EDIT:
The parse function is what causes the parse exception and the code for that method is included below for reference:
#Override public Symbol parse() throws java.lang.Exception {
int act; // current action code
Symbol lhs_sym = null; // the Symbol/stack element returned by a reduce
short handle_size, lhs_sym_num; // information about production being reduced with
boolean logging = "yes".equals(System.getProperty("debug"));
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
init_actions();
user_init();
// start
cur_token = scan();
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START", 0, start_state()));
tos = 0;
for (_done_parsing = false; !_done_parsing; ) {
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
if (act > 0) { // "shift"; thus, we shift to the encoded state by pushing it on the stack
if (logging) System.out.println("shift " + cur_token.sym);
cur_token.parse_state = act-1;
stack.push(cur_token);
tos++;
cur_token = scan();
} else if (act<0) { // "reduce"
if (logging) System.out.println("reduce " + ((-act)-1));
lhs_sym = do_action((-act)-1, this, stack, tos);
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; }
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
lhs_sym.parse_state = act;
stack.push(lhs_sym);
tos++;
} else { // "error"
if (logging) System.out.println("error");
syntax_error(cur_token);
done_parsing();
}
}
return lhs_sym;
}

How do I save a callback for later with node-addon-api?

I want my C library to be able to call a JS function multiple times. I got it to work using Nan but am having trouble converting it to N-API/node-addon-api.
How do I save a JS callback function and call it later from C?
Here's what I have using Nan:
Persistent<Function> r_log;
void sendLogMessageToJS(char* msg) {
if (!r_log.IsEmpty()) {
Isolate* isolate = Isolate::GetCurrent();
Local<Function> func = Local<Function>::New(isolate, r_log);
if (!func.IsEmpty()) {
const unsigned argc = 1;
Local<Value> argv[argc] = {
String::NewFromUtf8(isolate, msg)
};
func->Call(Null(isolate), argc, argv);
}
}
}
NAN_METHOD(register_logger) {
Isolate* isolate = info.GetIsolate();
if (info[0]->IsFunction()) {
Local<Function> func = Local<Function>::Cast(info[0]);
Function * ptr = *func;
r_log.Reset(isolate, func);
myclibrary_register_logger(sendLogMessageToJS);
} else {
r_log.Reset();
}
}
How do I do the equivalent with node-addon-api? All the examples I've seen immediately call the callback or use AsyncWorker to somehow save the callback. I can't figure out how AsyncWorker is doing it.
I got an answer from the node-addon-api maintainers which led me to this solution:
FunctionReference r_log;
void emitLogInJS(char* msg) {
if (r_log != nullptr) {
const Env env = r_log.Env();
const String message = String::New(env, msg);
const std::vector<napi_value> args = {message};
r_log.Call(args);
}
}
void register_logger(const CallbackInfo& info) {
r_log = Persistent(info[0].As<Function>());
myclibrary_register_logger(emitLogInJS);
}

CRM 2011 development: Get the following error if I try to get related entity: Object reference not set to an instance of an object

I try to get a related entity and get this error: Object reference not set to an instance of an object.
See below my code:
public IEnumerable<RUBAnnotation> GetAnnotationsByServiceRequestId(string serviceRequestId)
{
List<Annotation> annotationList = new List<Annotation>();
try
{
using (OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(organisationWebServiceUri, null, userCredentials, deviceCredentials))
{
organizationProxy.EnableProxyTypes();
var service = (IOrganizationService)organizationProxy;
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
Relationship rel = new Relationship("Incident_Annotation");
// get all incidents by incidentId
IEnumerable<Incident> incidents = from c in orgContext.CreateQuery<Incident>()
where c.Id == new Guid(serviceRequestId)
select c;
return GetAnnotationsEntities(incidents);
}
}
catch (Exception)
{
throw;
}
return null;
}
private List<RUBAnnotation> GetAnnotationsEntities(IEnumerable<Incident> incidents)
{
List<RUBAnnotation> annotationsList = new List<RUBAnnotation>();
try
{
foreach (Incident incident in incidents)
{
foreach (var annotation in incident.Incident_Annotation) // HERE OCCURS THE EXCEPTION!!
{
if (!string.IsNullOrEmpty(annotation.NoteText))
{
var customAnnotation = new RUBAnnotation();
customAnnotation.Id = annotation.Id.ToString();
if (annotation.Incident_Annotation != null)
{
customAnnotation.ServiceRequestId = annotation.Incident_Annotation.Id.ToString();
}
customAnnotation.Message = annotation.NoteText;
customAnnotation.CreatedOn = (DateTime)annotation.CreatedOn;
customAnnotation.UserId = annotation.CreatedBy.Id.ToString();
annotationsList.Add(customAnnotation);
}
}
}
}
catch (Exception e)
{
throw e;
}
return annotationsList;
}
Why do I get this error when I try to get incident.Incident_Annotation ? I think incident.Incident_Annotation is NULL, but why? Al my incidents have minimal 1 or more annotations.
Related entities must be explicitly loaded, you can find more information on this MSDN article:
MSDN - Access Entity Relationships

Who owns returned string from _bstr_t::wchar_t*, _bstr_t::char* operators?

_bstr_t::wchar_t*, _bstr_t::char* operators return string of different types.
Do I need to delete or free them? using which function?
After stepping the implementation using debugger, my conclusion is that there is no need to manually delete/free the returned string. The lifetime of the returned string is managed by _bstr_t internally.
See the following snippets from the implementation:
// Extract a const char_t*
//
inline _bstr_t::operator const char*() const throw(_com_error)
{
return (m_Data != NULL) ? m_Data->GetString() : NULL;
}
inline const char* _bstr_t::Data_t::GetString() const throw(_com_error)
{
if (m_str == NULL) {
m_str = _com_util::ConvertBSTRToString(m_wstr);
if (m_str == NULL && m_wstr != NULL) {
_com_issue_error(E_OUTOFMEMORY);
}
}
return m_str;
}
inline void _bstr_t::Data_t::_Free() throw()
{
if (m_wstr != NULL) {
::SysFreeString(m_wstr);
}
if (m_str != NULL) {
delete [] m_str;
}
}
It is also okay to use unnamed _bstr_t as follows because _bstr_t instance is destroyed after the constructor of CString has finished.
CString abc((LPCTSTR)_bstr_t(OLESTR("ABC")));
AfxMessageBox(abc);

Cannot convert lambda expression to type 'int' because it is not a delegate type

In this c# code I need to convert the userName value from string to int type.
Is anyone know please help me. I have got error as a compilation error "Cannot convert lambda expression to type 'int' because it is not a delegate type" like this.
ShoppingCartPartRecord cartRecord = null;
try {
cartRecord = _shoppingCartRepository.Get(r => r.Username == userName);
}
catch (InvalidOperationException ex) {
if (ex.Message == "Sequence contains more than one element") {
var badCarts = _shoppingCartRepository.Table.Where(x => x.Username == userName);
foreach (var shoppingCartPartRecord in badCarts) {
_shoppingCartRepository.Delete(shoppingCartPartRecord);
}
}
}
Thank you in advance.
Without the source to your repository we can only guess at what the methods do.
From the errors you are describing the get function expects either an index into an array or an integer primary key and so is the wrong function
You should be able to change the code as follows to achieve the desired effect
ShoppingCartPartRecord cartRecord = null;
try {
cartRecord = _shoppingCartRepository.Table.Single(r => r.Username == userName);
}
catch (InvalidOperationException ex) {
if (ex.Message == "Sequence contains more than one element") {
var badCarts = _shoppingCartRepository.Table.Where(x => x.Username == userName);
foreach (var shoppingCartPartRecord in badCarts) {
_shoppingCartRepository.Delete(shoppingCartPartRecord);
}
}
}

Resources