How to throw an exception in Azure Logic Apps? - exception

Is it possible to throw an exception in a Logic App?
Specifically, I'm trying to throw an exception inside of a scope. Then in the run after of the scope I'd check if it failed and inspect it for errors. I tried using a terminate inside of a scope, but that terminates the entire logic app run.

As an updated solution we can use Terminate control, Terminate control has 3 status: Failed, Canceled, and Succeeded.

Quick Answer (TL;DR)
Problem: MSFT Azure logic app throwing exceptions
Workaround: Use logic app Scope element to simulate throwing exceptions
Create a scope element to use as your "try-catch" block
Force the scope element to fail with an invalid command to simulate an exception
Allow the scope element to fail naturally and that will count as an exception too
Detailed Answer
Context
MSFT Azure logic app workflows
live version as of 2020-06-14
Problem
Scenario: Developer wishes to throw an exception or use try-catch semantics in a logic app
Solution
As of this writing, the live version of the product does not support this feature. There is a workaround.
Workaround
Use logic app scope element
add a conditional statement inside the scope element
If the conditional statement meets the failure condition, force an exception with a deliberately invalid command
for example create a variable assignment with the value int('__ERROR__')
If the conditional statement does not meet the failure condition, do nothing
The rest of the logic app consists of two paths
The first path runs on the success of the scope element
The second path runs on the failure of the scope element (failed, skipped, timed out)
Example
Create a scope element as a "try-catch" block
Create a variable compose element with an invalid command
int('__ERROR__') ## this will cause the enclosing scope to fail
## the string __ERROR__ cannot be cast to integer
Respond to exit status of the Scope element enclosing your exception
See also
related SO answer about forcing exceptions https://stackoverflow.com/a/61101945/42223

No, there is no Action or Connector directly analogous to something like a throw in C#.
The closest you can get right now would be to do something like use another LogicApp instead of a scope from which you can return a specific status code.

It seems like there still is no option for this inside Logic App or its little brother Power Automate / Microsoft Flow.
The way I have come up with and have used in some flows, is I simply add an action for something I know for a fact will fail.
The simplest (and probably the cheapest as the built-in actions cost less in Logic Apps, even if we are talking fractions of a dollar here either way) is probably to initialize a variable, e.g. called ThrowException with type of integer.
Then a "Set variable" action is added wherever I want my flow to fail, where I set the value (remember it is of type integer) to any string expression. I simply use the expression string('Exception').
Simple example screenshot
Since the value is set via an expression this is still a valid template, but will fail upon runtime when the value is actually being set.
After this, simply use parallel branches, with appropriate Run After settings, as usual.

Related

Discord.py assistance - How does the library forcibly call an asynchronous command function?

I have used many discord API wrappers, but as an experienced python developer, unfortunately I somehow still do not understand how a command gets called!
#client.command()
async demo(ctx):
channel = ctx.channel
await channel.send(f'Demonstration')
Above a command has been created (function) and it is placed after its decorator #client.command()
To my understanding, the decorator is in a way, a "check" performed before running the function (demo) but I do not understand how the discord.py library seemingly "calls" the demo function.....?? Is there some form of short/long polling system in the local imported discord.py library which polls the discord API and receives a list of jobs/messages and checks these against the functions the user has created?
I would love to know how this works as I dont understand what "calls" the functions that the user makes, and this would allow me to make my own wrapper for another similar social media platform! Many thanks in advance.
I am trying to work out how functions created by the user are seemingly "called" by the discord.py library. I have worked with the discord.py wrapper and other API wrappers before.
(See source code attached at the bottom of the answer)
The #bot.command() decorator adds a command to the internal lists/mappings of commands stored in the Bot instance.
Whenever a message is received, this runs through Bot.process_commands. It can then look through every command stored to check if the message starts with one of them (prefix is checked beforehand). If it finds a match, then it can invoke it (the underlying callback is stored in the Command instance).
If you've ever overridden an on_message event and your commands stopped working, then this is why: that method is no longer being called, so it no longer tries to look through your commands to find a match.
This uses a dictionary to make it far more efficient - instead of having to iterate over every single command & alias available, it only has to check if the first letters of the message match anything at all.
The commands.Command() decorator used in Cogs works slightly different. This turns your function into a Command instance, and when adding a cog (using Bot.add_cog()) the library checks every attribute to see if any of them are Command instances.
References to source code
GroupMixin.command() (called when you use #client.command()): https://github.com/Rapptz/discord.py/blob/24bdb44d54686448a336ea6d72b1bf8600ef7220/discord/ext/commands/core.py#L1493
As you can see, it calls add_command() internally to add it to the list of commands.
Adding commands (GroupMixin.add_command()): https://github.com/Rapptz/discord.py/blob/24bdb44d54686448a336ea6d72b1bf8600ef7220/discord/ext/commands/core.py#L1315
Bot.process_commands(): https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/bot.py#L1360
You'll have to follow the chain - most of the processing actually happens in get_context which tries to create a Context instance out of the message: https://github.com/Rapptz/discord.py/blob/24bdb44d54686448a336ea6d72b1bf8600ef7220/discord/ext/commands/bot.py#L1231
commands.Command(): https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/core.py#L1745

SolidJS: "computations created outside a `createRoot` or `render` will never be disposed" messages in the console log

When working on a SolidJS project you might start seeing the following warning message in your JS console:
computations created outside a `createRoot` or `render` will never be disposed
There are some information available on this in SolidJS' Github repository issues. But after reading them I was still not quite sure what this was all about and whether my code was really doing something wrong.
I managed to track down where it came from and find a fix for it based on the documentation. So I'm providing the explanation and the solution for those Googling this warning message.
In essence this is a warning about a possibility of a memory leak due to a reactive computation being created without the proper context which would dispose of it when no longer needed.
A proper context is created a couple of different ways. Here are the ones I know about:
By using the render function.
By using the createRoot function. Under the hood render uses this.
By using the createContext function.
The first is by far the most common way, because each app has at least one render function call to get the whole show started.
So what makes the code go "out of context"?
Probably the most common way is via async calls. The context creation with its dependency tree happens only when the synchronous portion of the code finishes running. This includes all the export default function in your modules and the main app function.
But code that runs at a later time because of a setTimeout or by being in an async function will be outside of this context and any reactive computations created will not be tracked and might stick around without being garbage collected.
An example
Let's say you have a data input screen and have a Save button on it that makes an API call to your server to save the data. And you want to provide a feedback to the user whether the operation succeeded or not, with a nice HTML formatted message.
[msg,setMsg] = createSignal(<></>)
async function saveForm(){
...
setMsg(<p>Saving your data.<i>Please stand by...</i></p>)
const result=await callApi('updateUser',formData)
if(result.ok){
setMsg(<p>Your changes were <b>successfully</b> saved!</p> )
} else {
setMsg(<p>There was a problem saving your data! <br>Error: </p><pre>{result.error}</pre> )
}
}
...
<div>
...
<button onClick={saveForm} >Save</button>
{msg()}
</div>
This will produce the above mentioned warning when the API call returns an error, but not the other times. Why?
The reason for this is that SolidJS considers the code inserts inside JSX to be reactive, ie: need to be watched and re-evaluated. So inserting the error message from the API call creates a reactive computation.
The solution
I found the solution at the very end of the SolidJS doc. It's a special JSX modifier: /*#once*/
It can be used at the beginning of a curly brace expression and it tells the SolidJS compiler to explicitly not to make this a reactive expression. In other words: it will evaluated once and only once when the DOM nodes are created from the JSX.
In the above example here's how to use it:
setMsg(<p>There was a problem saving your data! <br>Error: </p><pre>{/*#once*/ result.error}</pre> )
After this there will be no more warning messages :)
In my case, I had an input and when that input changed I re-created an SVG drawing. Because the SVG creation was an expensive operation, I added a debounce in the createEffect function which ran when the input changed. debounce is a technique to defer the processing until the input stops changing for at least X amount of time. It involved running the SVG generation code inside the setTimeout function, thus being outside of the main context. Using the /*#once*/ modifier everywhere where I inserted an expression in the generated JSX has fixed the problem.

Correct way to pass runtime configuration to elixir processes

I'm trying to deploy an app to production and getting a little confused by environment and application variables and what is happening at compile time vs runtime.
In my app, I have a genserver process that requires a token to operate. So I use config/releases.exs to set the token variable at runtime:
# config/releases.exs
import Config
config :my_app, :my_token, System.fetch_env!("MY_TOKEN")
Then I have a bit of code that looks a bit like this:
defmodule MyApp.SomeService do
use SomeBehaviour, token: Application.get_env(:my_app, :my_token),
other_config: :stuff
...
end
In production the genserver process (which does some http stuff) gives me 403 errors suggesting the token isn't there. So can I clarify, is the use keyword getting evaluated at compile time (in which case the application environment doest exist yet)?
If so, what is the correct way of getting runtime environment variables in to a service like this. Is it more correct to define the config in application.ex when starting the process? eg
children = [
{MyApp.SomeService, [
token: Application.get_env(:my_app, :my_token),
other_config: :stuff
]}
...
]
Supervisor.start_link(children, opts)
I may have answered my own questions here, but would be helpful to get someone who knows what they're doing confirm and point me in the right way. Thanks
elixir has two stages: compilation and runtime, both written in Elixir itself. To clearly understand what happens when one should figure out, that everything is macro and Elixir, during compilation stage, expands these macros until everything is expanded. That AST comes to runtime.
In your example, use SomeBehaviour, foo: :bar is implicitly calling SomeBehaviour.__using__/1 macro. To expand the AST, it requires the argument (keyword list) to be expanded as well. Hence, Application.get_env(:my_app, :my_token) call happens in compile time.
There are many possibilities to move it to runtime. If you are the owner of SomeBehaviour, make it accept the pair {:my_app, :my_token} and call Application.get_env/2 somewhere from inside it.
Or, as you suggested, pass it as a parameter to children; this code belongs to function body, meaning it won’t be attempted to expand during compilation stage, but would rather be passed as AST to the resulting BEAM to be executed in runtime.

ConcurrentModificationException in Android while accessing Shared Preferences

When I develop an android app, I run into the exception which I do not have any clue; I have googled related topics but none of them helped.
Fatal Exception: java.util.ConcurrentModificationException
java.util.HashMap$HashIterator.nextEntry (HashMap.java:806)
java.util.HashMap$KeyIterator.next (HashMap.java:833)
com.android.internal.util.XmlUtils.writeSetXml (XmlUtils.java:298)
com.android.internal.util.XmlUtils.writeValueXml (XmlUtils.java:447)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:241)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:181)
android.app.SharedPreferencesImpl.writeToFile (SharedPreferencesImpl.java:596)
android.app.SharedPreferencesImpl.access$800 (SharedPreferencesImpl.java:52)
android.app.SharedPreferencesImpl$2.run (SharedPreferencesImpl.java:511)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587)
java.lang.Thread.run (Thread.java:841)
Preferences are thread safe(!), but not process safe. The answer of
#mohan mishra simply not true, no need to synchronize everything. The problem here, as statet out in another question is, that per documentation you MUST NOT modify any instance that is returned by getStringSet and getAll
getStringSet()
Note that you must not modify the set instance returned by this call.
The consistency of the stored data is not guaranteed if you do, nor is
your ability to modify the instance at all.
getAll()
Note that you must not modify the collection returned by this method,
or alter any of its contents. The consistency of your stored data is
not guaranteed if you do.
To the other question
Documentation
Please ensure that you are not accessing the preferences from any type of background thread. Also all your methods to add to preference must be synchronised(if you have your own preference managing class)

cfthrow is this how you use it? (from Adobe's doc)

I was reading the documentation for cfthrow and came accross this
When to use the cfthrow tag
Use the cfthrow tag when your application can identify and handle
application-specific errors. One typical use for the cfthrow tag is in
implementing custom data validation. The cfthrow tag is also useful
for throwing errors from a custom tag page to the calling page.
For example, on a form action page or custom tag used to set a
password, the application can determine whether the password entered
is a minimum length, or contains both letters and number, and throw an
error with a message that indicates the password rule that was broken.
The cfcatch block handles the error and tells the user how to correct
the problem.
Have I been doing it wrong all this time or is this just a terrible use-case?
I was taught that exceptions shouldn't be used to handle regular application flow but for stuff that is somewhat out of your control. For example, a file being locked when you go to write to it.
A user breaking a password rule doesn't quite sound like something that's out of your control.
That is a poor example not a poor use case. I personally would pass in the parameters to a validation function and return a result that contained a pass or fail and a collection of failure messages to display to the user.
How I use exceptions is as follows.
Within functions. Let's say that you have a function that you are getting some data from the database and you are then constructing a structure from it. If the query returned has no values you have several options:-
You could return an empty structure and let the calling code deduce the problem from the fact the structure is empty. This is not ideal because then the application has to have complicated logic to address the missing data.
You could return a more complex datatype where one property is whether the process went ok and the actual data. Again this is not optimal as you have to then make this access the property on every call when the majority of the time you have data and again your application is dealing with this issue.
Or you could raise a custom exception with cfthrow indicating that there is no record that matches. This then means that you can choose to ignore the prospect of this error happening and let it bubble up to the onError handler or you could surround it in a try catch statement and deal with it there and then. This keeps your API clean and sensible.
Wrapping external errors let's say that you connect to an external API using cfhttp over https. Now this requires installing the certificate in your keystore otherwise it throws an error. If this certificate gets updated then it will start erroring again. In this instance I would wrap the call in a try catch and should this be the error I would wrap that in my own custom exception with a message detailing that we need to update the cert in the keystore so that any developer debugging it knows what to do to fix it without having to work it out. If it is not that particular error then I would cfrethrow it so that it bubbles up and is dealt with by whatever exception handling logic is above the call.
These are just a few examples, but there are more. To summarise I would say that throwing exceptions is a way of communicating up through the tiers of an application when something has occurred that is not the hoped for behaviour while keeping your API/Application logic clean and understandable.
It's really up to your discretion. It's extremely common in many languages to use exceptions for everything, including input validation.
Importantly, exceptions have nothing to do with something being in your control or not. For example, suppose that you have a fairly long and complicated module that uploads a file. There are many fail points in something like that: the file could be too big, the file could be the wrong format, etc. Without exceptions your only option is a lot of if/then checks and some kind of status return at the very end. With exceptions, all you have to do is use a set of cfthrows:
<cfthrow type="FileUpload.TooBig" message="The file size was #FileSize#, but the maximum size allowed is #MaxFileSize#">
<cfthrow type="FileUpload.WrongType" message="The file type was #FilType#, but the accepted types are #AcceptedTypeList#">
Then, whatever is calling the file upload function can catch either with <cfcatch type="FileUpload"> or catch a specific one (e.g. <cfcatch type="FileUpload.WrongType">).
Also, technically a user breaking a password is out of your control, in the sense that the user has determined the value for the password. That said, I loathe password rules as invariably they make it harder, not easier, to maintain security.