Event handlers with anonymous functions - event-handling

If I have the following code:
let submitButton = document.getElementById("submitButton");
Is the following event handler correct?
submitButton.addEventListener("click", "");

Related

Abort (HTTP 500) request when exception in request's handleEnd()

I'm using vert.x-web to implement a small service. One of my handlers for the end of the request (set via context.request().endHandler()) throws this NullPointerException:
2018-09-02 20:54:35,125 - ERROR [vert.x-eventloop-thread-1] (ContextImpl.java:345) - lambda$wrapTask$2()
Unhandled exception
java.lang.NullPointerException
at (My handler class)
at io.vertx.core.http.impl.HttpServerRequestImpl.handleEnd(HttpServerRequestImpl.java:417)
at io.vertx.core.http.impl.Http1xServerConnection.handleEnd(Http1xServerConnection.java:482)
at io.vertx.core.http.impl.Http1xServerConnection.handleContent(Http1xServerConnection.java:477)
at io.vertx.core.http.impl.Http1xServerConnection.processMessage(Http1xServerConnection.java:458)
at io.vertx.core.http.impl.Http1xServerConnection.handleMessage(Http1xServerConnection.java:144)
at io.vertx.core.http.impl.HttpServerImpl$ServerHandlerWithWebSockets.handleMessage(HttpServerImpl.java:712)
at io.vertx.core.http.impl.HttpServerImpl$ServerHandlerWithWebSockets.handleMessage(HttpServerImpl.java:619)
at io.vertx.core.net.impl.VertxHandler.lambda$channelRead$1(VertxHandler.java:146)
at io.vertx.core.impl.ContextImpl.lambda$wrapTask$2(ContextImpl.java:337)
at io.vertx.core.impl.ContextImpl.executeFromIO(ContextImpl.java:195)
at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:144)
Why doesn't this exception call my requests's exception handler? Why is it unhandled? I have the request's exception handler set to context.fail() (via context.request().exceptionHandler()). But it does not seem to have any effect.
Is there another exception handler I'm unaware of?
Edit: here is the minimal reproducing code:
Vertx vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.route().handler(context -> {
context.request()
.exceptionHandler(context::fail)
.endHandler(nothing -> { throw new NullPointerException("null"); })
.handler(buffer -> {});
});
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8080);
Expected behavior: context.fail(e) gets called and the connection closes with HTTP ERROR 500.
Got behavior: context is not failed, connection "hangs".
The exceptionHandler applies to the HttpServerRequest object. The method is inherited from the ReadStream interface. This callback is invoked whenever a problem occurs in the Vert.x/Netty code handling HTTP requests, not user code.
If you want to execute some code before the actual request processing, I would suggest to register a route and invoke RoutingContext#next in the handler:
Router router = Router.router(vertx);
router.route("/somepath").handler(routingContext -> {
// Handler invoked first
// Execute pre-processing logic
// And then...
context.next();
});
router.route("/somepath").handler(routingContext -> {
// Handler invoked second
// Execute processing logic
});
Then any failure in pre-processing logic will be caught and managed normally by the router.
Two things need to be pointed out here:
The hang is caused by the response is not explicitly ended (see HttpServerResponse#end().
To handle exception happened during request handling, add failure handler at route level (see Route#failureHandler()). Handling exception on request will only caught exception when reading the stream.
For example:
Router router = Router.router(vertx);
router.route().failureHandler(handler -> handler.response().end());
router.route().handler(routingContext -> routingContext.request().endHandler(handler -> {
throw new NullPointerException("exception here!");
}));
vertx.createHttpServer().requestHandler(router::accept).listen(8085);

Vertx - using the Router failureHandler for the errors in async calls

We have recently discovered the failureHandler in the Vertx router
We thought it could help us get rid of all the repetitive try-catch blocks we have. But alas, it seems that the exceptions that are thrown inside the callbacks are not caught by the failureHandler.
Example: below, the failureHandler is called only for the 3rd case:
// Get the user details
router.get("/user").handler(ctx -> {
ctx.response().headers().add("content-type", "application/json");
// some async operation
userApiImpl.getUser(ctx, httpClient, asyncResult -> {
// ctx.response().setStatusCode(404).end(); //1
// throw new RuntimeException("sth happened"); //2
ctx.fail(404); //3
});
});
// ============================
// ERROR HANDLER
// ============================
router.get("/user").failureHandler(ctx -> {
LOG.info("Error handler is in the action.");
ctx.response().setStatusCode(ctx.statusCode()).end("Error occurred in method");
});
Is this as expected?
Can we somehow declare a global try-catch in a router for the exceptions occurring in the async context?
It is expected that sending a response manually with an error code does not trigger the failure handler.
It should be triggered if:
the route path matches
a handler throws an exception or ctx.fail() is invoked
Here's an example:
Route route1 = router.get("/somepath/path1/");
route1.handler(routingContext -> {
// Let's say this throws a RuntimeException
throw new RuntimeException("something happened!");
});
Route route2 = router.get("/somepath/path2");
route2.handler(routingContext -> {
// This one deliberately fails the request passing in the status code
// E.g. 403 - Forbidden
routingContext.fail(403);
});
// Define a failure handler
// This will get called for any failures in the above handlers
Route route3 = router.get("/somepath/*");
route3.failureHandler(failureRoutingContext -> {
int statusCode = failureRoutingContext.statusCode();
// Status code will be 500 for the RuntimeException or 403 for the other failure
HttpServerResponse response = failureRoutingContext.response();
response.setStatusCode(statusCode).end("Sorry! Not today");
});
See the error handling section of the Vert.x Web documentation

Is it possible to send CAN messages out of a callback function?

I have following problem: I would like to send CAN messages out of a callback function. This callback function is called by an timerobject. Everytime when the callback function is executed it should send the CAN message.
I coded:
canch = canChannel('PEAK-System', 'PCAN_USBBUS1');
configBusSpeed(canch, 1000000)
start(canch)
canch.Database = canDatabase('\\psf\Home\Desktop\02 CAN DBC\CAN4.dbc');
message = canMessage (canch.Database,'IPSS_RX_1_1ms');
transmitPeriodic(canch,message, 'On', 0.01);
T= timer('ExecutionMode','fixedrate','Period',0.2,...
'TimerFcn',#TEST_timer_callback_fcn,'StopFcn','disp(''Timer has stopped'')');
start(T)
Callback function:
function TEST_timer_callback_fcn(src,event)
message.Signals.In_ti= 39;
The CAN Channel starts - but the message is not send.
Can somebody help?
It's likely that your timer function simply doesn't have access to the message object (i.e. it exists in a different scope). One option is to nest your timer function within a function where you initialize message. Alternatively, you can pass message to your timer function. You could do this by changing the timer creation line to this:
T = timer('ExecutionMode','fixedrate','Period',0.2,...
'TimerFcn',#(~,~) TEST_timer_callback_fcn(message),...
'StopFcn','disp(''Timer has stopped'')');
And the callback function to this:
function TEST_timer_callback_fcn(message)
message.Signals.In_ti= 39;

rxjs: Can an Observable implementation invoke onNext on the same thread of execution?

In ReactiveX an Observable might invoke
the following methods
onNext
onError
onCompleted
according to a very clear contract http://reactivex.io/documentation/contract.html
I am writing the code for the Observable and I have realized that under certain circumstances I might invoke onNext within the same thread of execution.
Is that a mistake ?
For example, if I have code like this:
// call onNext twice on the same thread execution.
o.onNext(event1);
o.onNext(event2);
Should I rewrite it like this:
// call onNext and then schedule the next call via setTimeout
o.onNext(event1);
setTimeout(function() { o.onNext(event2); },0);
= = = = = = = =
Clarification: why am I asking ?
In a browser, let's imagine the observer wants to update an HTML element with the content of onNext then if it is called serially that code would not work.
function onNext() {
count++;
htmlElement.innerHTML = 'count:'+count; // <-- this will work only if onNext is invoked on different thread of executions.
}

DataReceived Event handler not receiving messages

I'm using the below code to receive the messages using serial port event handler. But it dosent receives any.I am not getting errors. The code breaks in "string msg = comport.Readline()" Am i doing something wrong ?
public partial class SerialPortScanner : Form
{
private SerialPort comPort = new SerialPort();
public SerialPortScanner()
{
InitializeComponent();
comPort.Open();
comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comPort.IsOpen == true)
{
string msg = comPort.ReadLine();
MessageBox.Show(msg);
}
}
}
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception.
Source : Check this
ReadLine depends on having a NewLine character. You might have better luck with the Read method. See also the BytesToRead property.