Background task with result leads to compiler error FS0073 - f#

I am new to F# language but as far as I read backgroundTask syntax isn't limited to being only tasks with no result, however, when I change the following code I get compiler error FS0073
Severity Code Description Project File Line Suppression State
Error FS0073 internal error: Undefined or unsolved type variable: 'a
let sendSerializedPayload (writePayload, commandType: BaseCommand.Type) =
Log.Logger.LogDebug("{0} Sending message of type {1}", prefix, commandType)
backgroundTask { // <-- this used to be just task
try
do! connection.Output |> writePayload
return true
with ex ->
Log.Logger.LogWarning(ex, "{0} Socket was disconnected exceptionally on writing {1}", prefix, commandType)
post operationsMb ChannelInactive
return false
}
Is there something that I am doing wrong or not understanding or there is a compiler problem with backgroundTasks with results (I don't get such errors when switching from task to backgroundTask for task that does not have result?

Related

Set a given Publishers Failure type to Never in Combine

Is there a way to transform a given AnyPublisher<AnyType, SomeError> to AnyPublisher<AnyType, Never>?
A publisher with Never as error type mean that it can't throw error at all. It will always deliver a value.
To obtain a publisher that can never throw errors you have 2 solutions:
1/ Catch all possible errors:
let publisher: AnyPublisher<AnyType, SomeError> = //...
publisher.catch { error in
// handle the error here. The `catch` operator requires to
// return a "fallback value" as a publisher
return Just(/* ... */) // as an example
}
2/ If you are sure that there no errors can be thrown by the publisher, you can use .assertNoFailure(), that will convert your publisher. Note that is an error pass through the .assertNoFailure(), your app will crash immediately.
Use the replaceError operator. This requires that you emit an AnyType value that will be sent down the pipeline from this point if an error arrives from upstream.
For example:
URLSession.shared.dataTaskPublisher(for: url)
.map {$0.data} // *
.replaceError(with: Data()) // *
// ...
From this point on down the pipeline, we are guaranteed that either the Data from the data task completion or (if there is a networking error) an empty Data will be received. The Failure type from this point down the pipeline is Never.

Erlang How to mix try catch with if

I'm very new in Erlang.
I want to make function to check ban word.
But I got syntax errors..
How to use try catch with if else statement?
check_banword(Word, BlackWord) ->
try
Res = string:rstr(Word, BlackWord),
if Res > 0 ->
true;
true ->
false
catch
false
end.
Two problems in the code:
Missing end after if
Catch syntax is incorrect, catch matches exceptions to values, you cannot have just a value there.
The code with changes enabling it to compile looks like
check_banword(Word, BlackWord) ->
try
Res = string:rstr(Word, BlackWord),
if
Res > 0 ->
true;
true ->
false
end
catch
_ -> false
end.
In this case, you don't actually need the if, you can use try with patterns and guards. When used in this way, try looks like a case expression with a catch section at the end. (Note that only the part between try and of is "protected" by the catch - in this case, it doesn't make any difference because the rest of the code cannot raise an error.)
Also note that you need to specify what type of exception you want to catch, one of error, exit and throw. If you don't specify the type of exception, it defaults to throw - and that's not what you want here, since string:rstr never throws anything, it can only raise errors if the arguments are of an incorrect type.
So that would be:
check_banword(Word, BlackWord) ->
try string:rstr(Word, BlackWord) of
Res when Res > 0 ->
true;
_ ->
false
catch
error:_ -> false
end.
And there is a wider question: should you actually use try here? If an error occurs in this function, it means that the arguments were not strings, and that is the caller's responsibility. Since there isn't anything that this function can do to fix the problem, I'd say that it shouldn't catch the error but let it propagate to the caller. (This is known as Erlang's "let it crash" philosophy.)

How to return a function value from pcall() in lua

My code (psuedo)
function foo(cmd)
return load(cmd) --Note that this could cause an error, should 'cmd' be an invalid command
end
function moo()
return "moo"
end
function yoo(something)
something.do()
end
cmd = io.read() --Note that a syntax error will call an error in load. Therefore, I use pcall()
local result, error = pcall(cmd)
print(result)
This code looks okay, and works, but my problem is if I type in moo() then result will only show whether or not the command was executed without an error (If the command calls an error, error will have its value).
On another note, if I want to call yoo(), I won't get a return value from it, so I want pcall()'s true / false (or any alternate means other than pcall())
Is there an alternate way to call moo(), get a return value, and also be able to catch any errors?
NOTE: I couldn't find any try catch equivalent other then pcall / xpcall.
A bit outdated but still without proper answer...
What you are looking for is a combination of both load() and pcall()
Use load()to compile the entered string cmd into something that can be executed (function).
Use pcall() to execute the function returned by load()
Both functions can return error messages. Get syntax error description from load() and runtime error description from pcall()
function moo()
return "moo"
end
function yoo(something)
something.do_something()
end
cmd = io.read()
-- we got some command in the form of a string
-- to be able to execute it, we have to compile (load) it first
local cmd_fn, err = load("return "..cmd);
if not cmd_fn then
-- there was a syntax error
print("Syntax error: "..err);
else
-- we have now compiled cmd in the form of function cmd_fn(), so we can try to execute it
local ok, result_or_error = pcall(cmd_fn)
if ok then
-- the code was executed successfully, print the returned value
print("Result: "..tostring(result_or_error));
else
-- runtime error, print error description
print("Run error: "..result_or_error)
end
end

How do I fail a script running in Bitbucket Pipelines?

When a pipeline runs a node series of commands, how can I trigger a fail within the pipeline?
I have tried the following:
const failBuild = function(message) {
console.error('Deploy failed: ', message)
throw new Error('Deploy failed')
}
I see the "Deploy failed" message, but the pipeline still says "Success".
Bb Pipelines fail when a command exits with a non-zero exit code. So, if you want the pipeline to fail, you have to make sure the code is not 0.
In your case (note for people reading this later: see comments), you get 0 as exit status, because the throw is executed in a promise, but then catched in the promise’s catch() function – which does neither stop execution nor have any influence on the exit code.
Solution: explicitly throw an error in the catch() function.
For anyone else who might be struggling with this...
You need to return a non zero as already mentioned, I find the easiest way to do this is by passing a negative integer to PHP's exit() function.
https://php.net/manual/en/function.exit.php
if($condition == true)
{
// Whatever we were doing, it worked YAY!!
exit();
}
else
{
// Something went wrong so fail the step in the pipeline
exit(-1);
}
The accepted answer states:
Solution: explicitly throw an error in the catch() function.
So if I understand that correctly, it suggests you should write the script as:
async function main() { throw "err"; }
main().catch(e => { throw e; });
However, this does not work: the exit code is still 0, and the console displays a nasty warning:
> node "main.js"
(node:32996) UnhandledPromiseRejectionWarning: err
(node:32996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:32996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
> $?
0
The correct way to bubble up the error to the node process is:
process.on('unhandledRejection', up => { throw up });
async function main() { throw "err"; }
main();
This way, you get teh following result:
> node "main.js"
test2.js:1
process.on('unhandledRejection', up => { throw up });
^
err
> $?
1
Which is a little bit better (except the stacktrace is not very clear).

Print the exmpp Packet to Raw XML string

How to print the Packet type to raw XML string ? In the example https://github.com/processone/exmpp/blob/master/examples/echo_client.erl the echo_packet(MySession, Packet) -> function takes the parameter Packet which is of xmlel record type. As mentioned in the post https://stackoverflow.com/a/31020654/579689 tried the function xml:element_to_binary/1 but it did not work.
When i tried to print using the following expression
io:format("Received Presence stanza:~n~p~n~n", [xml:element_to_binary({xmlel,<<"message">>,[{<<"xml:lang">>,<<"en">>},{<<"type">>,<<"chat">>},{<<"to">>,<<"x">>},{<<"id">>,<<"aaf6a">>}],[{xmlcdata,<<"\n">>},{xmlel,<<"body">>,[],[{xmlcdata,<<"wewe">>}]},{xmlcdata,<<"\n">>},{xmlel,<<"active">>,[{<<"xmlns">>,<<"http://jabber.org/protocol/chatstates">>}],[]},{xmlcdata,<<"\n">>},{xmlel,<<"time">>,[{<<"xmlns">>,<<"urn:server-time">>},{<<"stamp">>,"2015-06-23T22:48:24Z"}],[]}]})]).
received following error
=ERROR REPORT==== 12-Oct-2015::09:06:01 ===
Error in process <0.30.0> with exit value: {undef,[{xml,element_to_binary,[{xmlel,<<7 bytes>>,[{<<8 bytes>>,<<2 bytes>>},{<<4 bytes>>,<<4 bytes>>},{<<2 bytes>>,<<1 byte>>},{<<2 bytes>>,<<5 bytes>>}],[{xmlcdata,<<1 byte>>},{xmlel,<<4 bytes>>,[],[{xmlcdata,<<4 bytes>>}]},{xmlcdata,<<1 byte>>},{xmlel,<<6 bytes>>,[{<<5 bytes>>,<<37 bytes>>}],[]},{xmlcdata,<<1 byte>>},{xmlel,<<4 bytes>>,[{<<5 bytes>>,<<15 bytes>>},{<<5 bytes>>,"2015-06-23T22:48:24Z"}],[]}]}],[]},{echo_client,loop,1,[{file,"../examples/ech...
Error {undef,[{xml,element_to_binary,[list of N args]}]} tells you that function xml:element_to_binary/N is undefined.
Looking through xml module of the project you may try element_to_string instead of element_to_binary.
However from the point of efficiency exmpp_xml:document_to_iolist/1 will suit you better

Resources