I just installed Elmah (https://code.google.com/p/elmah/) for my ASP.NET application.
Is it possible to log a message without creating an Exception first?
catch(Exception e)
{
Exception ex = new Exception("ID = 1", e);
ErrorSignal.FromCurrentContext().Raise(ex);
}
So is it possible to do:
ErrorSignal.FromCurrentContext().log("Hello I am testing Elmah");
Yes, you can use ErrorSignal without throwing an exception.
ErrorSignal.FromCurrentContext().Raise(new NotSupportedException());
For the custom message, you can create a custom exception.
var customEx = new Exception("Hello I am testing Elmah", new NotSupportedException());
ErrorSignal.FromCurrentContext().Raise(customEx);
Try this
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Your message"));
I know this is an old question, but if you don't want to create an exception you can also use
var error = new Error
{
Source = eventType.ToString(),
Type = $"Trace-{eventType}",
Message = message,
Time = DateTime.UtcNow
};
ErrorLog.GetDefault(HttpContext.Current).Log(error);
as shown in this answer.
Related
I want to do the exception handling in Jmeter.Webdriver Webdriver Sampler
Please let me , How to use try/catch block in Jmeter.Webdriver webdriver Sampler ?
You can do this via normal JavaScript try block, here is an example of taking a screenshot when error occurs:
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait = new support_ui.WebDriverWait(WDS.browser, 5)
var exception = null
WDS.sampleResult.sampleStart()
try {
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('Not existing link')))
} catch (err) {
WDS.log.error(err.message)
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(java.io.File('screenshot.png'))
exception = err
} finally {
throw (exception)
}
WDS.sampleResult.sampleEnd())
Don't forget to "throw" the error after you handle it otherwise it will be "swallowed" and you get a false positive result.
See The WebDriver Sampler: Your Top 10 Questions Answered article for more tips and tricks
Surround the code with try block and add catch block at the end by giving variable name to capture the exception. (in the example, it is exc)
try as follows:
try{
WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
var pkg = JavaImporter(org.openqa.selenium)
WDS.browser.findElement(pkg.By.id('what')) // there is no such element with id what
WDS.sampleResult.sampleEnd()
}
catch(exc){ //exc variable name
WDS.log.error("element not found" + exc)
}
in the JMeter log, you can see the complete trace of NoSuchElementException, which is raised when trying to find the element by id with the values as what, which is not present in the HTML.
Note: use View Results in Table to see the Sampler response time.
Reference:
https://jmeter-plugins.org/wiki/WebDriverSampler/
Reference Image:
It is same as how do you do in other IDEs like eclipse.
you can see below code
//try block starts here
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element"))).click();
}
catch(Exception e)
{
WDS.log.info("Exception is : " +e);//you can print the exception in jmeter log.
}
double quotes should be replaced with the single quote if you are using javascript Since the BeanShell is easy and it is similar to java use BeanShell as much as possible
If I specify
flyway.callbacks=com.myclass.CustomCallBack
it gets called fine, but I notice it seems to suppress the SQL callback functionality. Is there any way to have both? I notice there's a SqlScriptFlywayCallback, but that's one of your 'internal' classes....
Currently the only way is to refer both to the internal class and your own. Please file an enhancement request in the issue tracker.
As a simple workaround, you can initialize the SqlScriptFlywayCallback as Axel suggested. Here's how I did it, given an initialized instance of flyway:
DbSupport dbSupport;
try {
dbSupport = DbSupportFactory.createDbSupport(flyway.getDataSource().getConnection(), false);
} catch (SQLException e) {
throw new RuntimeException("Could not get connection to database");
}
final FlywayCallback runSqlCallbacks = new SqlScriptFlywayCallback(
dbSupport,
flyway.getClassLoader(),
new Locations(flyway.getLocations()),
new PlaceholderReplacer(flyway.getPlaceholders(),
flyway.getPlaceholderPrefix(),
flyway.getPlaceholderSuffix()),
flyway.getEncoding(),
flyway.getSqlMigrationSuffix()
);
flyway.setCallbacks(
runSqlCallbacks,
new MyCallback(...));
How do I get to the content of Refit.ApiException?
Depending on what the inner content is, I want to let the user know how to proceed. So I see that thrown exception has the following content ...
Content "{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}"
The question is, how do I access that?
You can add one catch block for ApiException. and you can get content from this catch block.
See below:
catch (ApiException ex)
{
var content = ex.GetContentAs<Dictionary<String, String>>();
Debug.WriteLine(ex.Message);
}
Going through the RestService class https://github.com/paulcbetts/refit/blob/master/Refit/RestService.cs
figured out I could use the GetContentAs method
So just did this..
((Refit.ApiException)ex).GetContentAs<Dictionary<String, String>>())
to parse out the key value content.
As an extra heads-up:
GetContentAs<T>(); is now deprecated.
Use GetContentAsAsync<T>(); instead.
With the latest version of API Exception, you can use the following code for getting the API content:
public static void HandleException( Exception exception )
{
var content = ((Refit.ApiException)exception).GetContentAsAsync<Dictionary<string, string>>();
var message = content.Result.FirstOrDefault( pair => pair.Key == "message" ).Value;
Debug.WriteLine(message);
}
I made 3 Ajax processes to run the below code at the same time.
but one of the processes throw exception that message says "The underlying provider failed on Open."
try{
orderRepository orderRepo = new orderRepository(); // get context (Mysql)
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
}catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
}
And, I run the 1 Ajax call that failed before, then It passes through.
It happen to 1 of 3 (Ajax) process, sometimes, 2 of 5 process.
I guess it because all process try to using Database same time. but I couldn't find the solution.
This is my connection string,
<add name="EFMysqlContext" connectionString="server=10.0.0.10;User Id=root;pwd=xxxx;Persist Security Info=True;database=shop_db" providerName="Mysql.Data.MySqlClient" />
Anybody know the solution or something I can try, please advise me.
Thanks
It sounds like a problem because of concurrent connection with SQL Server using same username. Have you tried destroying/disposing the repository(or connection) object after using it?
Give it a try:
try{
using( orderRepository orderRepo = new orderRepository()) // get context (Mysql)
{
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
} // orderRepo object automatically gets disposed here
catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
} }
Not sure if it matters, but your provider name is Mysql.Data.MySqlClient and not MySql.Data.MySqlClient (if it is case-sensitive, this could be the cause).
Using Tridion 2009, SP1, hence the old COM+ TOM API. I'm trying to get information of a PublishTransaction but getting an error each time I call the PublishTransaction.Information property.
Here is my code:
try
{
var pubTrans = (PublishTransaction)tdse.GetObject("tcm:0-166535-66560",
EnumOpenMode.OpenModeView);
Console.WriteLine("transaction id=" + pubTrans.ID);
Console.WriteLine("transaction itemtype=" + pubTrans.itemType.ToString());
Console.WriteLine("transaction info=" + pubTrans.Information);
}
catch (Exception e)
{
Console.WriteLine(e.Message, e.StackTrace);
}
Above, the transaction ID and Item Type print fine. I have other code where the Delete method works fine, but any time I try and get the Information, it blows up.
Here is the error:
<tcm:Error xmlns:tcm="http://www.tridion.com/ContentManager/5.0" ErrorCode="D"
Category="18" Source="Kernel" Severity="1">
<tcm:Line Cause="false" MessageID="16138">
<![CDATA[Unable to get Information of Unknown (tcm:0-166535-66560).]]>
<tcm:Token>RESID_4485</tcm:Token><tcm:Token>Information</tcm:Token>
<tcm:Token>RESID_4663</tcm:Token><tcm:Token>tcm:0-166535-66560</tcm:Token>
</tcm:Line>
<tcm:Line ErrorCode="D" Cause="true"><![CDATA[Type mismatch]]></tcm:Line>
<tcm:Details>
<tcm:CallStack>
<tcm:Location>PublishTransaction.Information</tcm:Location>
<tcm:Location>PublishTransaction.Information</tcm:Location>
</tcm:CallStack>
</tcm:Details>
</tcm:Error>
I've searched the SDL Tridion World forum and couldn't find the answer. Am I missing a hotfix, should I contact Support, or is there another way to get the transaction info?
I am not really sure (without digging further at this time of night), but is the 'Information' property actually an XMLElement rather than a string as the docs say? When you use a debugger, are you able to place a watch on this property to see what it contains?
I tried this in another way to get the PublishTransaction Information. Below is the code:-
PublishTransaction pubTrans = (PublishTransaction)tdse.GetObject(
"tcm:0-4294103-66560",
EnumOpenMode.OpenModeView,
null,
XMLReadFilter.XMLReadNull);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(pubTrans.GetXML(XMLReadFilter.XMLReadAll));
XmlNamespaceManager nameSpace = new XmlNamespaceManager(xmlDoc.NameTable);
nameSpace.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
nameSpace.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
Console.WriteLine("transaction id=" + pubTrans.ID);
Console.WriteLine("transaction itemtype=" + pubTrans.itemType.ToString());
EnumPublishTransactionState transState = pubTrans.get_State();
if (transState == EnumPublishTransactionState.Failed)
Console.WriteLine("transaction info=" +
xmlDoc.SelectSingleNode("/tcm:PublishTransaction/tcm:Data/tcm:Information",
nameSpace).InnerText);
I don't have a working environment, so I am just looking into whatever existing code I have available. This is snippet from the Event system which deletes a Queue item only when you have Admin privileges:
public void OnPublicationPublishPost(Publication publication, IXMLDOMDocument2 publishResult)
{
TDSE tdse = Utilities.GetTDSEInstance();
publishResult.setProperty("SelectionNamespaces", "xmlns:tcm=\"http://www.tridion.com/ContentManager/5.0\"");
PublishTransaction publishTransaction = Utilities.GetTridionItem<PublishTransaction>(publishResult.selectSingleNode("/*/*").attributes[2].text, null) as PublishTransaction;
User user = Utilities.GetTridionItem<User>(publishResult.selectSingleNode("/tcm:PublishResponse/tcm:PublisherRequest/tcm:User").attributes[0].text, null) as User;
TDSPrivileges isAdmin = user.privileges;
if (isAdmin != TDSPrivileges.TdsPrivilegeSystemAdministrator)
{
publishTransaction.Delete();
}
}